Parse ISO 8601 date ending in Z with Python
The ‘Z’ at the end of an ISO 8601 date indicates that the time is in UTC (Coordinated Universal Time). To parse a string containing a date in that format with a ‘Z’ at the end we can use the datetime module. e.g.
from datetime import datetime
iso_date_string = "2023-05-29T10:30:00Z"
parsed_date = datetime.fromisoformat(iso_date_string[:-1]) # Removing the 'Z' at the end
print(parsed_date)
However, when comparing to a time-zoned datetime
e.g. datetime.now(pytz.timezone('Europe/London'))
we get the following error TypeError: can't compare offset-naive and offset-aware datetimes
.
We need to make the parsed datetime object timezone aware, to set it to UTC we can do the following
from datetime import datetime
import pytz
iso_date_string = "2023-05-29T10:30:00Z"
parsed_date = datetime.fromisoformat(iso_date_string[:-1]) # Removing the 'Z' at the end
utc_timezone = pytz.timezone('UTC')
aware_date = parsed_date.replace(tzinfo=utc_timezone)
print(aware_date)