timezone class of datetime module in Python

The timezone class implements the abstract class tzinfo in a specific way. For example, the timezone does not support Daylight saving time (DST).

Timezone Updated 9 Aug 2021 1 min read

Overview

  • As Earth rotates at the face of the Sun, days and nights occur. When it is day at some parts of the Earth, it is night at the other side of the geoid. When it is day at some parts of the Earth, the sun might be at some position of rising or setting (from the perspective of Earth). As it is morning in New York, it is evening in Tokyo and it is afternoon in London. While it is still afternoon in London, afternoon has already happened in Tokyo 9 hours prior and it is yet to happen in New York (in next four hours).
  • Thus these cities are all in different time zones. These time zones are either ahead or behind in time to an observer at the prime meridian. The time difference between one place and the UTC (calculated at prime meridian) is the UTC offset.
  • Time duration to specify the time difference from UTC and a name for it together make the timezone class. The time duration is specified as a timedelta instance.
  • The class timezone is the Python standard library implementation of the abstract class tzinfo.

Example

python
# Example Python program that constructs

            # a timezone object and attaches it to a time object

            from datetime import timedelta, timezone, time

# A time duration of one hour

            td = timedelta(hours = 8)

# All timezones are + or - some timedelta from UTC

            # Singapore is 8 hours ahead of UTC

            tz = timezone(td, name="Singapore Time")

# 10 AM in Singapore

            t = time(hour = 10, tzinfo = tz)

print(t)

            print(t.tzinfo)

Output

Output
10:00:00+08:00

Singapore Time