If I use fromisoformat
(in Python3.11), then Z
is parsed as UTC
:
In [15]: dt.datetime.fromisoformat('2020-01-01T03:04:05Z')
Out[15]: datetime.datetime(2020, 1, 1, 3, 4, 5, tzinfo=datetime.timezone.utc)
But how can I parse it if I want to pass the format explicitly?
I tried '%Y-%m-%dT%H:%M:%S%Z'
, but it errors:
In [16]: dt.datetime.strptime('2020-01-01T03:04:05Z', '%Y-%m-%dT%H:%M:%S%Z')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[16], line 1
----> 1 dt.datetime.strptime('2020-01-01T03:04:05Z', '%Y-%m-%dT%H:%M:%S%Z')
File /usr/lib/python3.11/_strptime.py:568, in _strptime_datetime(cls, data_string, format)
565 def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
566 """Return a class cls instance based on the input string and the
567 format string."""
--> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
569 tzname, gmtoff = tt[-2:]
570 args = tt[:6] + (fraction,)
File /usr/lib/python3.11/_strptime.py:349, in _strptime(data_string, format)
347 found = format_regex.match(data_string)
348 if not found:
--> 349 raise ValueError("time data %r does not match format %r" %
350 (data_string, format))
351 if len(data_string) != found.end():
352 raise ValueError("unconverted data remains: %s" %
353 data_string[found.end():])
ValueError: time data '2020-01-01T03:04:05Z' does not match format '%Y-%m-%dT%H:%M:%S%Z'
I know I can get a result with '%Y-%m-%dT%H:%M:%SZ', but that does actually parse the Z
as a timezone:
In [17]: dt.datetime.strptime('2020-01-01T03:04:05Z', '%Y-%m-%dT%H:%M:%SZ')
Out[17]: datetime.datetime(2020, 1, 1, 3, 4, 5)