How to Create and Convert Timezone Aware Dates with Python

Gavin Wiener
2 min readMay 14, 2020

--

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:

  1. Understanding timezone aware and not timezone aware
  2. Assigning at timezone
  3. 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

import pytz

To see all the timezones Pytz has,

for tz in pytz.all_timezones:
print(tz)

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>)

If we print(utcnow)

2020–05–13 08:39:07.109762+00:00

We’re timezone aware!

Converting Between Timezones

Now, if we want to convert between timezones, datetime objects have a useful astimezone() function.

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 brisbane now,

datetime.datetime(2020, 5, 13, 18, 11, 14, 960814, tzinfo=<DstTzInfo ‘Australia/Brisbane’ AEST+10:00:00 STD>)

If we print it

2020–05–13 18:11:14.960814+10:00

Summary

  1. Know the timezone you’re working with
  2. Assign the timezone to your datetime object if it is not aware with .replace(tzinfo=<timezone>)
  3. Use astimezone(<new timezone>) to convert to another timezone

Happy times, happy converting!

Sign-up here to receive automation tips, case studies, and guides on the mistakes you maybe making on your automation journey.

And follow me on Twitter where I post about my journey, automation, and business growth.

--

--

Gavin Wiener

I'm a coder and freelancer from South Africa with 5+ years experience in automations, integrations and API's using Python and Django.