What is zoneinfo.ZoneInfo(key) in Python?
Definition
ZoneInfois a class in thezoneinfomodule.ZoneInfocreates an instance of zone from thekeypassed to the constructor.- This
keyis a string that indicates the name of a zone file in the system timezone database. - Example keys are
America/Los_Angeles,Europe/Paris…
Note: The
zoneinfomodule is only available in Python versions 3.9 or higher.
Syntax
ZoneInfo(key)
Parameters
key: TheZoneInfoclass constructor acceptskeyas a parameter.
Return value
ZoneInfo returns a ZoneInfo object that is constructed from the first matching data source on the search path.
Example 1
In the example below, we:
- Import the
ZoneInfoclass from thezoneinfomodule. - Construct the
ZoneInfoobject. - Pass
America/Los_Angelesas thekeyto the constructor. - Store
ZoneInfoinaand print to the console.
from zoneinfo import ZoneInfo# constructing the ZoneInfo objecta = ZoneInfo("America/Los_Angeles")print(a)
Example 2
In the example below, we:
- Import the
ZoneInfoclass in line 1. - In lines 3 and 4, create
ZoneInfoobjectsaandbfrom the same key,America/Los_Angeles. - In line 6, assert if
aandbare equal.
If the
ZoneInfoobjects are constructed from the samekeyanddata sourcepath, then they point to the same object.
The code snippet outputs:
-
Succeeded:ifaandbare equal. -
Assertion Error: ifaandbare not equal.
from zoneinfo import ZoneInfo# constructing ZoneInfo objectsa = ZoneInfo("America/Los_Angeles")b = ZoneInfo("America/Los_Angeles")# asserting the ZoneInfo objects created aboveassert a is b
Example 3
In the code below, we:
- Import
ZoneInfoanddatatimein lines 1 and 2. - Create DateTime
dt1anddt2of the same date with two timezones asAmerica/Los_Angeles,Pacific/Kwajalein, by assigningZoneInfoobjects totzinfo. - Run the code snippet below to see the difference in DateTime.
from zoneinfo import ZoneInfofrom datetime import datetime#creating datetime for different timezonesdt1 = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))dt2 = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("Pacific/Kwajalein"))#printing the dt1 and dt2print("America/Los_Angels --> "+ str(dt1))print("Pacific/Kwajalein --> "+ str(dt2))
Example 4
In the code snippet below, we deliberately pass an incorrect key to the ZoneInfo constructor to raise ZoneInfoNotFoundError.
If the
keypassed toZoneInfoconstructor is not valid or it cannot find the zone file in the database, then the constructor will raiseZoneInfoNotFoundError.
from zoneinfo import ZoneInfo# deliberately passing the wrong key to raise errora = ZoneInfo("America/xyz")