Monday, November 18, 2024
Google search engine
HomeLanguagesPython – datetime.tzinfo()

Python – datetime.tzinfo()

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

RELATED ARTICLES

Most Popular

Recent Comments