Suppose I have the following datetime object:
>>> dt
datetime.datetime(2015, 5, 13, 18, 5, 55, 320000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))
I can print that object in ISO 8601 format like so:
>>> dt.isoformat()
'2015-05-13T18:05:55.320000-07:00'
Under Python 3.4, I can parse the string of an ISO 8601 string if I remove the colon in the time zone:
>>> import re
>>> ts='2015-05-13T18:05:55.320-07:00'
>>> tf="%Y-%m-%dT%H:%M:%S.%f%z"
>>> tsm=re.sub(r'([+-]\d+):(\d+)$', r'\1\2', '2015-05-13T18:05:55.320-07:00')
>>> tsm
'2015-05-13T18:05:55.320-0700'
>>> datetime.datetime.strptime(tsm, tf)
datetime.datetime(2015, 5, 13, 18, 5, 55, 320000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))
Under Python 2.7, the situation is worse since the %z
does not seem to work as documented:
>>> tsm='2015-05-13T18:05:55.320-0700'
>>> tf="%Y-%m-%dT%H:%M:%S.%f%z"
>>> datetime.datetime.strptime(tsm, tf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f%z'
Note that is the same format string that does work under Python 3.4.
Question: Other than using dateutil (which works great), is there a reasonable way to parse a ISO 8601 date string with datetime.strptime or something else in the standard library?