0

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)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65

1 Answers1

0

To parse a date string in the format '%Y-%m-%dT%H:%M:%SZ' using datetime.strptime() and interpret the 'Z' as UTC, you can use the pytz library to create a timezone object for UTC and pass it as the tzinfo argument to datetime.strptime(). Here's an example:

import datetime as dt
from pytz import timezone

utc = timezone('UTC')
dt_string = '2020-01-01T03:04:05Z'
dt_obj = dt.datetime.strptime(dt_string, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=utc)
print(dt_obj)

The output will be:

2020-01-01 03:04:05+00:00

You can also use datetime.datetime.fromisoformat method.

dt_obj = dt.datetime.fromisoformat(dt_string)
print(dt_obj)

This will give you the same result of 2020-01-01 03:04:05+00:00 with timezone information.