Python 3.6 DateTime Strptime Returns 错误,而 Python 3.7 运行良好

Python 3.6 DateTime Strptime Returns error while Python 3.7 works well

我刚刚为日期数据创建了一个数据类型,return是一个 datetime.datetime 对象

代码如下:

import datetime


class Date:
    def __new__(cls, dateTime, *args, **kwargs):
        return datetime.datetime.strptime(dateTime, "%Y-%m-%dT%H:%M:%S.%f%z")

所以每次我给这个 class 一个 ISO-8601 它应该 return 来自字符串的日期时间对象...

Python 3.7 示例:

Date("2018-12-09T08:56:12.189Z")                                        
# Returns => datetime.datetime(2018, 12, 9, 8, 56, 12, 189000, tzinfo=datetime.timezone.utc)

这很好用,但是当我在 Python 3.6 或 Python 3.5 上使用它时:

# Python 3.5 Traceback
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
    (data_string, format))
ValueError: time data '2018-12-09T08:56:12.189Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

# Python 3.6 Traceback
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2018-12-09T08:56:12.189Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

好奇怪,请问是什么原因造成的?我该如何解决?

好的,2 天后,我查看了Python 3.7 changelog, and I found out support for Z as a UTC offset was added in Python 3.7. See this issue on the Python issue tracker, which is primarily about adding support for colons, but also mentions Z support further down the page. Also see the datetime docs,上面写着

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

在我的 class 上,我不得不将时间格式更改为:

datetime.datetime.strptime(dateTime, "%Y-%m-%dT%H:%M:%S.%fZ")

我把最后的 %z 改成了 Z,硬编码了偏移量。