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
ZoneInfoclass 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/Kwajaleinzone = 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
ZoneInfoanddatetime. -
In lines 5 and 6, we construct
ZoneInfoobjectszone1andzone2with different keys. -
In lines 9 and 10, we create two different
datetimeinstances from the same date with different keys. -
In lines 12 and 13, we print the date and time for the previously created
dt1anddt2.
This code outputs the date and time for different zones.
from zoneinfo import ZoneInfofrom datetime import datetime# key as Pacific/Kwajaleinzone1 = ZoneInfo("Pacific/Kwajalein")zone2 = ZoneInfo("America/New_York")# creating datetime for different zonesdt1 = 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}]")