Working with timezones in python

  • Post author:
  • Post category:Python

Working with timezones in python

This very short post looks at converting dates between timezones.

The most prevalent library for timezones in python is pytz, which can be installed by:

pip install pytz

It allows you to manipulate times by assigning times to timezones using Olsen timezones (e.g. Europe/London).

Let’s first import our required packages: datetime and pytz.

In [1]:
import datetime
import pytz

Now let’s take a look at converting a local Sydney time to UTC.

We need to first localize the time using our local timezone.

Then we normalize the time to our target timezone.

In [2]:
dt = datetime.datetime(2000, 1, 1, 18, 30)
2000-01-01 18:30:00
In [3]:
local_tz = pytz.timezone('Australia/Sydney')
dt = local_tz.localize(dt)
2000-01-01 18:30:00+11:00
In [4]:
target_tz = pytz.timezone('UTC')
dt = target_tz.normalize(dt)
2000-01-01 07:30:00+00:00

Using pytz Olsen timezones rather than just defining the offsets ourselves is incredibly useful.

One of the reasons for this is that timezones for a given location can change.

For example, if we’re in Germany we have 2 timezones, thanks to daylight savings time:

  • Central European Time (CET, UTC+0100)
  • Central European Summer Time (CEST, UTC+0200)

Let’s see this in action, let’s take the same local time in the winter and in the summer and see what happens.

In [5]:
winter_dt = datetime.datetime(2017, 1, 1, 14, 0)
print(winter_dt.strftime("Winter Local Time: %H:%M"))

summer_dt = datetime.datetime(2017, 7, 1, 14, 0)
print(summer_dt.strftime("Summer Local Time: %H:%M"))

local_tz = pytz.timezone('Europe/Berlin')
target_tz = pytz.timezone('UTC')

winter_dt = local_tz.localize(winter_dt)
summer_dt = local_tz.localize(summer_dt)

winter_dt = target_tz.normalize(winter_dt)
summer_dt = target_tz.normalize(summer_dt)

print(winter_dt.strftime("Winter UTC Time: %H:%M"))
print(summer_dt.strftime("Summer UTC Time: %H:%M"))
Winter Local Time: 14:00
Summer Local Time: 14:00
Winter UTC Time: 13:00
Summer UTC Time: 12:00