Python日期时间:十进制数字的strftime()代码

3
为什么会出现错误?
>>> an = datetime.datetime.now(); an
datetime.datetime(2020, 3, 8, 22, 52, 19, 256487)
>>> datetime.datetime.strftime(an, '%-d')
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    datetime.datetime.strftime(an, '%-d')
ValueError: Invalid format string

基于这些来源(sources1, sources2),我预计得到"8"

它在我的电脑上可以运行。你的Python版本是多少? - Sam
1
请尝试执行以下代码:datetime.datetime.strftime(an, '%#d') - William
1个回答

7

你链接的页面中提到:

Python文档包含C标准(1989年版本)所需的所有格式代码,并且这些代码在所有具有标准C实现的平台上都可以使用。请注意,C标准1999版添加了其他格式代码。这些包括用于非零填充数字的代码,可以通过在百分号(%)后附加破折号(-)(UNIX)或井号(#)(Windows)来获得。

因此,在Linux上可以正常工作:

datetime.datetime.strftime(an, '%-d')

而且这在Windows上运行:

datetime.datetime.strftime(an, '%#d')

有趣的是,在Python strftime文档中我没有看到任何一个被提及。整个特性在Python中可能完全是无意的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接