What is ZoneInfo.key in Python?

ZoneInfo.key is a read-only attribute of the ZoneInfo class. This means that you cannot insert keys, but can only read from the IANA time zone database.

This attribute is used to look up the time zone specified in the IANA time zone database . Some examples of keys are: Pacific/Kwajalein, America/New_York, Europe/Paris etc.

IANA is a database that is present in your computer and contains time zone keys.

For zones constructed from files without specifying the value of the key parameter, this will be set to None.

The ZoneInfo class is aailable in Python 3.9 or above.

Code

Example 1

In the example below, we import the ZoneInfo class from zoneinfo module, and we pass the Pacific/Kwajalein key as a parameter to the ZoneInfo class constructor.

from zoneinfo import ZoneInfo
# key as Pacific/Kwajalein
zone = ZoneInfo("Pacific/Kwajalein")
print(str(zone))

Example 2

The following example shows the use of different time zone keys.

In this code snippet:

  • In lines 1 and 2, we import ZoneInfo and datetime.

  • In lines 5 and 6, we construct ZoneInfo objects zone1 and zone2 with different keys.

  • In lines 9 and 10, we create two different datetime instances from the same date with different keys.

  • In lines 12 and 13, we print the date and time for the previously created dt1 and dt2.

This code outputs the date and time for different zones.

from zoneinfo import ZoneInfo
from datetime import datetime
# key as Pacific/Kwajalein
zone1 = ZoneInfo("Pacific/Kwajalein")
zone2 = ZoneInfo("America/New_York")
# creating datetime for different zones
dt1 = datetime(2020, 4, 1, 3, 15, tzinfo=zone1)
dt2 = datetime(2020, 4, 1, 3, 15, tzinfo=zone2)
print(f"{dt1.isoformat()} [{dt1.tzinfo}]")
print(f"{dt2.isoformat()} [{dt2.tzinfo}]")

Free Resources