为什么会报错?
>>> 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
最佳答案
The Python docs contain all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes. These include codes for non-zero-padded numbers, that can be obtained by appending a dash (-) (UNIX) or hash (#) (Windows) after the percent (%) sign.
因此,这适用于 Linux:
datetime.datetime.strftime(an, '%-d')
这适用于 Windows:
datetime.datetime.strftime(an, '%#d')
有趣的是,我在 Python strftime docs 中没有看到他们中的任何一个被提及。 .整个功能在 Python 中也可能是无意的。
关于Python 日期时间 : strftime() codes for decimal numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591282/