WRITELOOP

HOW TO CONVERT A STRING WITH TIMEZONE (UTC) INFORMATION IN PYTHON (3.5+ PROBABLY) TO A PYTHON UTC DATETIME

2018 August 6
In [1]: from datetime import datetime, timezone
...:
...: def deserialize(date):
...:     format = '%Y-%m-%dT%H:%M:%SZ'
...:     deserialized_date: datetime.strptime(date, format).replace(tzinfo=timezone.utc)
...:     return deserialized_date
...:
In [2]: example_str_date_with_utc_info_on_iso8601 = '2017-01-25T12:00:00Z'
In [3]: deserialize_str_date_with_utc_info_to_datetime_utc_aware = deserialize(example_str_date_with_utc_info_on_iso8601)
In [4]: deserialize_str_date_with_utc_info_to_datetime_utc_aware
Out[4]: datetime.datetime(2017, 1, 25, 12, 0, tzinfo=datetime.timezone.utc)

Curiosity: the Z on example_str_date_with_utc_info_on_iso8601 means “Zulu”. The Z is a short form to say UTC 0 which is the real Universal Time (e.g. as opposed to -3, which is Brazil’s UTC time).