Python 3.6 DateTime Strptime Returns error while Python 3.7 works well

限于喜欢 提交于 2019-12-10 13:09:02

问题


I just created a data type for my date data, which returns a datetime.datetime object

Here is the code:

import datetime


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

So everytime I give this class an ISO-8601 it should return the datetime object from the string...

Python 3.7 Example:

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

This works damn well, but when I use it on Python 3.6 or 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'

It's so weird, What causes the problem? How can I fix it?


回答1:


Ok, after 2 days, I checked the 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, which say

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

On my class, I had to change the time format to this:

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

I changed the %z at the end to Z, hardcoding the offset.



来源:https://stackoverflow.com/questions/53291250/python-3-6-datetime-strptime-returns-error-while-python-3-7-works-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!