How to Create and Convert Timezone Aware Dates with Python
This short quick tip serves more as a reminder for myself. I know I’m not speaking just for myself when I say converting dates and times between timezones can be a real headache. This is a quick summary of handling timezone conversions with datetime objects in Python
This quick article will describe:
- Understanding timezone aware and not timezone aware
- Assigning at timezone
- Converting to another timezone
Intro to Timezone Aware and Not Timezone Aware
We’ll need two Python libraries for this, pytz and Python’s datetime .
from datetime import datetime
now = datetime.now()- Returns a datetime object in your current timezone, but it is not timezone-aware
utcnow = datetime.utcnow() —Returns a datetime object in utc timezone, but SURPRISE, it is not timezone-aware
If you want to convert any datetime from one timezone to another timezone, we first need to know the original timezone, and to assign it to datetime object
In the example above, we know
utcnow is UTC, but it is not timezone-aware. We must assign a timezone. In your project, maybe you’ve decided to save all your timezones in your local timezone. Generally, it is recommended to always save in UTC.
Assign a Timezone
Let’s bring in Pytz
To see all the timezones Pytz has,
for tz in pytz.all_timezones:
Let’s assign a timezone to
utcnow from earlier.
utcnow = utcnow.replace(tzinfo=pytz.utc)
In the terminal and type
utcnow you’ll see,
datetime.datetime(2020, 5, 13, 8, 39, 29, 220134, tzinfo=<UTC>)
We’re timezone aware!
Converting Between Timezones
Now, if we want to convert between timezones,
datetime objects have a useful
Let’s say I want to convert to Brisbane (in Australia) timezone (I work with a client in Australia, which inspired this article).
brisbane = utcnow.astimezone(pytz.timezone(“Australia/Brisbane”))
If we type
datetime.datetime(2020, 5, 13, 18, 11, 14, 960814, tzinfo=<DstTzInfo ‘Australia/Brisbane’ AEST+10:00:00 STD>)
- Know the timezone you’re working with
- Assign the timezone to your datetime object if it is not aware with
astimezone(<new timezone>)to convert to another timezone
Happy times, happy converting!