Sometimes, we want to make a time zone aware datetime object in Python.
In this article, we’ll look at how to make a time zone aware datetime object in Python.
How to make a timezone aware datetime object in Python?
To make a time zone aware datetime object in Python, we can use the pytz module.
For instance, we write:
import datetime
import pytz
unaware = datetime.datetime(2020, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2020, 8, 15, 8, 15, 12, 0, pytz.UTC)
now_aware = pytz.utc.localize(unaware)
assert aware == now_aware
We create datetime objects with the datetime.datetime method.
And as pass in the time zone as the last argument of datetime.datetime to create a UTC datetime.
Without the time zone argument, then datetime object isn’t time zone aware.
To convert a time zone unaware datetime to a time zone aware datetime, we call pytz.utc.localize.
Therefore, aware and non_aware are the same since we made both datetimes time zone aware, have the same time zone, and have the same date and time.
Conclusion
To make a time zone aware datetime object in Python, we can use the pytz module.