【发布时间】:2015-04-04 13:45:19
【问题描述】:
所以在 Python 3 中,您可以使用 .isoformat() 生成 ISO 8601 日期,但您不能将 isoformat() 创建的字符串转换回 datetime 对象,因为 Python 自己的 datetime 指令不正确匹配。也就是说,%z = 0500 而不是 05:00(由 .isoformat() 生成)。
例如:
>>> strDate = d.isoformat()
>>> strDate
'2015-02-04T20:55:08.914461+00:00'
>>> objDate = datetime.strptime(strDate,"%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\Lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Python34\Lib\_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2015-02-04T20:55:08.914461+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
来自 Python 的 strptime 文档:(https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior)
%z UTC 偏移量,格式为 +HHMM 或 -HHMM(如果 对象是幼稚的)。 (空),+0000,-0400,+1030
因此,简而言之,Python 甚至不遵守自己的字符串格式化指令。
我知道 Python 中的 datetime 已经很糟糕了,但这确实超出了不合理的范围,进入了愚蠢的境地。
告诉我这不是真的。
【问题讨论】:
-
您是否考虑过从等格式字符串中剥离最后一个冒号,然后解析回日期时间对象?这是一种解决方法,仍然可以优雅地完成。
-
@OliverW。我确实考虑过这一点,最后我最终放弃并安装了 python-dateutil。我实际上也不认为这是一个好的解决方案。我认为那些负责 python 的人需要仔细看看他们对 datetime 做了什么。到目前为止,我已经放弃了,并且会像其他人一样跳过篮球。
-
我一直对 python 印象特别深刻,甚至有 strptime 和 strftime 这样的函数,我什至没有花时间注意到这个特殊的缺陷,因为如前所述,它可以相当优雅地避免。
-
我同意,这太荒谬了——本机平台可以转换为 ISO 日期,但不能将其转换回来,除非您使用其他第三方模块。
-
从 Python 3.7 开始,
%z引入了一个新功能:Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.
标签: python datetime iso8601 rfc3339