Python 日期时间 : strftime() codes for decimal numbers

标签 python datetime

为什么会报错?

>>> 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

基于此来源(sources1sources2)我预计 “8”

最佳答案

page you linked说:

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/

相关文章:

python - 检查两个有序列表的匹配

javascript - 将时间戳转换为日期会在结果中给出不同的时区吗?

c# - 日期时间转换和解析

python - python 格式的 flake8 (E902) TokenError

python - 如何在类型提示系统中使用通用(高级)类型变量?

python - 使用 pytz 和 UTC 转换丢失 DST 信息

oracle - 使用星期六作为星期结束日期计算oracle中的星期结束日期

mysql - 如何在数据库中保存 future (!)日期

python - Pandas .at 不工作并且数据框没有改变

Python 在尝试读取文件夹中的第二个文件时返回错误