VOOZH about

URL: https://www.geeksforgeeks.org/python/python-datetime-tzinfo/

⇱ datetime.tzinfo() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

datetime.tzinfo() in Python

Last Updated : 12 Jul, 2025

datetime.tzinfo() class is an abstract base class in Python that provides the interface for working with time zone information. The tzinfo class itself does not store any time zone data; instead, it is intended to be subclassed. The subclass can provide the logic to convert datetime objects to and from different time zones.

Methods of tzinfo

The methods available for implementation in tzinfo base class are :

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

1. utcoffset(self, dt)

This method should return the offset of the time zone (in minutes) from UTC for a given datetime object dt. Example: For a UTC+5 hour time zone, this method will return a timedelta object representing 5 hours.


Output
UTC Offset: 5:00:00

Explanation: In the example, the method is defined to return timedelta(hours=5), which means the time zone is UTC +5 hours. The utcoffset() method is used to get the time difference from UTC for a given date-time object.

2. dst(self, dt)

dst() method returns the daylight saving time (DST) adjustment. If the time zone observes daylight saving, it returns a timedelta representing the shift during DST; otherwise, it returns None or timedelta(0).


Output
Daylight Saving Time (DST): 1:00:00

Explanation: In the example, dst(self, dt) returns timedelta(hours=1), which means the time zone has a 1-hour DST adjustment. This method is useful for handling daylight saving transitions.

3. tzname(self, dt)

tzname() method returns the name of the time zone. This is typically a string representing the time zone abbreviation (e.g., "UTC", "PST").


Output
Time Zone Name: MyTimeZone

Explanation: In the example, tzname(self, dt) returns the string "MyTimeZone", which is a custom name for the time zone. This method helps in identifying the time zone.

4. fromutc(self, dt)

fromutc() method is used to convert a UTC time into the corresponding local time of the time zone. It adds the UTC offset to the given UTC time to return the local time.


Output
UTC Time: 2025-04-05 10:00:00
Local Time: 2025-04-05 15:00:00

Explanation:

  • The MyTimeZone class defines the custom time zone by implementing utcoffset, dst, tzname, and fromutc methods.
  • The fromutc() method is used to convert the given UTC time (utc_time) to the local time by adding the UTC offset (+5 hours in this case).
  • The output will show both the UTC time and the converted local time.

Related Articles:

Comment
Article Tags: