Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
python3

What is ZoneInfo.key in Python?

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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}]")

RELATED TAGS

communitycreator
python
python3

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring