The Wayback Machine - https://web.archive.org/web/20240710232006/https://www.geeksforgeeks.org/python-datetime-tzinfo/
Open In App

Python – datetime.tzinfo()

Last Updated : 27 Feb, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The DateTime class provides various functions to manipulate the date and time intervals. The DateTime object which you use in datetime.now() is actually the object of the DateTime class. These objects help us use the functions on dates and times.

Note: For more information, refer to Python datetime module with examples

DateTime.tzinfo()

The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class.

The instance of the tzinfo class can be passed to the constructors of the datetime and time objects. It finds its applications in situations such as the conversion of local time to UTC or to account for daylight saving time.

Naive and Aware datetime objects

A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An Aware datetime object contains the time zone information embedded in it.

The methods available for implementation in tzinfo base class are :

  • utcoffset(self, dt)
  • dst(self, dt)
  • tzname(self, dt)
  • fromutc(self, dt)

utcoffset()

It returns the offset of the datetime instance passed as argument.

What does this offset refer to ?

It refers to the time zone offset which denotes how many hours the time zone is ahead from the Coordinated Universal Time or Universal Time Coordinate (UTC). The offset is written as +00:00. For example: for Asia/Taipei, it is written as UTC +08:00.

It takes up the time of a datetime object and returns the difference between time in datetime object and the time of same point in UTC. It returns the offset in minutes east of UTC. If the local time is west of UTC, it would be negative. The general implementation form is given below:

For fixed offset :

 def utcoff(self, dt):
      return constant

For time aware objects :

def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

dst()

It is abbreviated as Day-light Saving Time. It denotes advancing the clock 1 hour in summer time, so that darkness falls later according to the clock. It is set to on or off. It is checked based on a tuple containing 9 elements as follows :

(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0)

A private function is written in order to return either 0, 1 or -1 depending on these 9 elements. Based on that the value of dst(self, dt) is decided. The function is written in the class where dst() is defined. It is written as:




def _isdst(self, dt):
  
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
  
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
  
        return tt.tm_isdst > 0


Here mktime() takes this tuple and converts it to time in seconds passed since epoch in local time. Then, tm_isdst() is used along with mktime. It returns the values as follows :

‘1’ – Daylight Saving ON
‘0’ – Daylight Saving OFF
‘-1’ – Daylight Saving information unknown

After adding this code to the class, the dst() can be defined as given below based on the conditions.

For fixed offset class :

 def dst(self, dt):
        return ZERO

For time aware objects :

 def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

tzname()

This is used to find the time zone name of the datetime object passed. It returns a Python String object.

Example:




import datetime as dt
from dateutil import tz
  
  
tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname()
  
print("datetime.now() :", tz_string)
  
NYC = tz.gettz('Europe / Berlin')  
dt1 = dt.datetime(2015, 5, 21, 12, 0) 
dt2 = dt.datetime(2015, 12, 21, 12, 0, tzinfo = NYC) 
  
print("Naive Object :", dt1.tzname())
print("Aware Object :", dt2.tzname())


Output:

datetime.now() : UTC
Naive Object : None
Aware Object : CET

fromutc()

This function takes up the date and time of the object in UTC and returns the equivalent local time. It is used mostly for adjusting the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dt’s date and time data will be returned as an equivalent local time.

Note: It will raise ValueError if dt.tzinfo is not self or/and dst() is None.

The general implementation is given below:

def fromutc(self, dt):
    dt_offset = dt.utcoffset()
    dt_dst = dt.dst()
    delta = dt_offset - dt_dst  
               
    if delta:
          dt += delta   
          dtdst = dt.dst()
          
    if dtdst:
          return dt + dtdst
    else:
          return dt


Previous Article
Next Article

Similar Reads

Python | Pandas Timestamp.tzinfo
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.tzinfo attribute is used to check the timezone of the given Timestamp object. If the timezone is not set then it return
2 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python datetime.tzname() Method with Example
tzname() method is used in the DateTime class of module DateTime. This method is used to return the time zone name of the DateTime object passed, as a string. Syntax: tzname() Return type: It will return the time zone name of the DateTime object passed, as a string. So first we need to import the module DateTime, and to get the timezone of the exac
2 min read
Create Python Datetime from string
In this article, we are going to see how to create a python DateTime object from a given string. For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user. Syntax: datetime.strptime(date_string, format)Converting string
4 min read
Manipulate Date and Time with the Datetime Module in Python
Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python's standard utility modules we can easily manipulate date and time according to our own need
9 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg