ZoneInfo
is a class in the zoneinfo
module.ZoneInfo
creates an instance of zone from the key
passed to the constructor.key
is a string that indicates the name of a zone file in the system timezone database.America/Los_Angeles
, Europe/Paris
…Note: The
zoneinfo
module is only available in Python versions 3.9 or higher.
ZoneInfo(key)
key
: The ZoneInfo
class constructor accepts key
as a parameter.ZoneInfo
returns a ZoneInfo
object that is constructed from the first matching data source
on the search path.
In the example below, we:
ZoneInfo
class from the zoneinfo
module.ZoneInfo
object.America/Los_Angeles
as the key
to the constructor.ZoneInfo
in a
and print to the console.from zoneinfo import ZoneInfo# constructing the ZoneInfo objecta = ZoneInfo("America/Los_Angeles")print(a)
In the example below, we:
ZoneInfo
class in line 1.ZoneInfo
objects a
and b
from the same key, America/Los_Angeles
.a
and b
are equal.If the
ZoneInfo
objects are constructed from the samekey
anddata source
path, then they point to the same object.
The code snippet outputs:
Succeeded:
if a
and b
are equal.
Assertion Error
: if a
and b
are 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
In the code below, we:
ZoneInfo
and datatime
in lines 1 and 2.dt1
and dt2
of the same date with two timezones as America/Los_Angeles
, Pacific/Kwajalein
, by assigning ZoneInfo
objects to tzinfo
.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))
In the code snippet below, we deliberately pass an incorrect key
to the ZoneInfo
constructor to raise ZoneInfoNotFoundError
.
If the
key
passed toZoneInfo
constructor 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")