Prerequisite: Python – datetime.tzinfo()
Python supports datetime module to perform manipulations for date and time. Datetime module allows the user to perform various date and time-related arithmetic operations, extraction of various time frames and formatting of output in different formats. Objects of these types are immutable. The module can be imported into the Python workspace using the following command :
The datetime objects also support an additional time zone attribute, which is optional. This attribute can be assigned to an instance of a subclass of the tzinfo class. The tzinfo object class can cater to the following requirements, that is, capturing information about the fixed offset from UTC time, that is, either the UTC itself or North American EST and EDT timezones, the name of the corresponding time zone, and also if the daylight saving time is currently in effect. tzinfo is an abstract base class. Any arbitrary concrete subclass of tzinfo may need to implement methods of its own. A timezone’s offset refers to how many hours the timezone is from Coordinated Universal Time (UTC).
Determining the type of datetime object using tzinfo
There are two kinds of objects, naive and aware, In case, the object does not contain any timezone information, then the datetime object is naive, else aware. In the case of a naive object, tzinfo returns None.
In case, we need to use aware datetime objects, a time zone can be explicitly specified. The pytz library can be used to localize the created datetime object, which provides information about the created time zone. Naive datetime and aware datetime objects can’t be compared, otherwise, it will throw an error.
Replacing timezone of the datetime object
A naive timezone object is instantiated using the datetime.now() object. The new time zone can be specified explicitly using the pytz.timezone() module. The specified time zone is then used further. The replace method is invoked over the datetime object and tzinfo argument is set to the replaced timezone value. This value is then extracted using the astimezone() method over the naive timezone object and taking changed timezone as its argument.
Current timezone 2021-02-12 20:20:50.668454 Replaced timezone 2021-02-12 20:20:50.668454-07:53
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.