Back to Course

Intermediate Python

0% Complete
0/0 Steps
Lesson 18 of 33
In Progress

Timezones and Daylight Savings Time

Working with timezones and daylight savings time can be a complex task in Python. The datetime module provides several functions and classes for handling timezones and daylight savings time, as well as performing arithmetic with dates and times in different timezones.

Timezone Object

The datetime module provides the tzinfo class for representing timezones. To create a timezone object, you can subclass the tzinfo class and implement the utcoffset(), dst(), and tzname() methods.

Here is an example of a timezone class for the Eastern Time zone:

import datetime

class EasternTimeZone(datetime.tzinfo):
    def utcoffset(self, dt):
        return datetime.timedelta(hours=-5)

    def dst(self, dt):
        return datetime.timedelta(0)

    def tzname(self, dt):
        return 'Eastern Time'

# create a timezone object
et = EasternTimeZone()

In this example, the utcoffset() method returns the offset from UTC (Coordinated Universal Time) in hours, the dst() method returns the daylight savings time offset in hours, and the tzname() method returns the name of the timezone.

You can use the timezone object to create datetime objects with a specific timezone. For example:

import datetime

# create a datetime object with a specific timezone
dt = datetime.datetime(2022, 1, 20, 12, 34, 56, tzinfo=et)
print(dt)  # Output: 2022-01-20 12:34:56-05:00

In this example, the datetime object is created with the Eastern Time timezone.

You can also use the astimezone() method to convert a datetime object to a different timezone. For example:

import datetime

# create a timezone object for Pacific Time
pt = PacificTimeZone()

# convert the datetime object to Pacific Time
dt2 = dt.astimezone(pt)
print(dt2)  # Output: 2022-01-20 10:34:56-07:00

In this example, the datetime object is converted from Eastern Time to Pacific Time using the astimezone() method.


To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.