ZoneInfo class in Python

The ZoneInfo class works in tandem with a DateTime instance and supports IANA databases along with supporting the daylight saving time.

Zoneinfo Class Updated 8 Dec 2020 1 min read

Overview

  • The ZoneInfo class represents an IANA timezone.
  • The ZoneInfo class is intended to work with a DateTime instance.
  • When a DateTime instance is created with a ZoneInfo object it supports the IANA timezone as well as the daylight saving time.

Example

python
# Example Python program that converts

            # a time from one timezone to another

            # using ZoneInfo class

            from zoneinfo import ZoneInfo

            from datetime import datetime, timedelta

# Create an instance of ZoneInfo

            ianaTimeZone = "America/New_York";

            timeZone      = ZoneInfo(ianaTimeZone);

# Specify date and time

            year     = 2021;

            month     = 1;

            date      = 1;

            hours     = 13;

# Create a datetime instance with a given ZoneInfo

            regionalTime = datetime(2020, 12, 31, 13,

                                      tzinfo = timeZone);

            print("Time in %s:"%ianaTimeZone);

            print("%s %s"%(regionalTime, regionalTime.tzname()));

# Create another instance of ZoneInfo

            ianaTimeZone         = "America/Chicago";

            timeZone             = ZoneInfo(ianaTimeZone);

# Convert from one time zone to another time zone zone

            newTime = regionalTime.astimezone(timeZone);

            print("Time in %s:"%ianaTimeZone);

            print("%s %s"%(newTime, newTime.tzname()));

Output

Output
Time in America/New_York:

            2020-12-31 13:00:00-05:00 EST

            Time in America/Chicago:

            2020-12-31 12:00:00-06:00 CST