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

Python – datetime.tzinfo()

Last Updated : 27 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:





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:





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
How to change the Pandas datetime format in Python?
Prerequisites: Pandas The date-time default format is "YYYY-MM-DD". Hence, December 8, 2020, in the date format will be presented as "2020-12-08". The datetime format can be changed and by changing we mean changing the sequence and style of the format. Function used strftime() can change the date format in python. Syntax: strftime(format) Where, fo
1 min read
How to add and subtract days using DateTime in Python?
As we know date and time are used in programs where we have to keep track of date and time, so it is necessary to have a module to manipulate date and time. In Python, a DateTime module deals with dates and times. Datetime module is built into Python standard library. Datetime module consists of the following classes: Name Description 1.dateIt show
3 min read
Python DateTime astimezone() Method
The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz. Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will have the local date, time, and time zone. Syntax:
2 min read
Basic DateTime Operations in Python
Python has an in-built module named DateTime to deal with dates and times in numerous ways. In this article, we are going to see basic DateTime operations in Python. There are six main object classes with their respective components in the datetime module mentioned below: datetime.datedatetime.timedatetime.datetimedatetime.tzinfodatetime.timedeltad
12 min read
How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately. Here, we deal with a special date objec
2 min read
Python SQLite - Working with Date and DateTime
SQLite does not support built-in DateTime storage a class, but SQLite allows us to work with timestamp types. We can store and retrieve Python date and datetime information stored in the SQLite database tables by converting them to Python date and datetime types and vice-versa. While inserting the datetime value, the python sqlite3 module converts
4 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
isocalendar() Function Of Datetime.date Class In Python
The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 full weeks.ISO years do not have any fractional weeks
2 min read
fromtimestamp() Function Of Datetime.date Class In Python
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method. Syntax: @classmethod fromtimestamp(timestamp) Parameters: This fun
2 min read
ctime() Function Of Datetime.date Class In Python
The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character length.Week is printed as a three-letter word.Sun, M
2 min read
Isoweekday() Method Of Datetime Class In Python
Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursday5Friday6Satur
3 min read
Datetime.replace() Function in Python
Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters. Syntax: Datetime_object.replace(year,month,day,hour,minute,second,microsecond,tzinfo) Parameters: year: New year value in range-[1,9999],month: New month value in range-[1,12],day: New day value in range-[1,31],hour: New hour value in range
2 min read
Isoformat() Function Of Datetime.date Class In Python
The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date needs to be represented using a 4-digit year followed by a two-digit month and a two-digit
3 min read
timetuple() Function Of Datetime.date Class In Python
timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time is in effect. The year, month, and day fields of th
2 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Python - datetime.toordinal() Method with Example
datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object. If January 1 of year 1 has ordinal number 1 then, January 2 year 1 will have ordinal number 2, an
2 min read
weekday() Function Of Datetime.date Class In Python
The weekday() of datetime.date class function is used to return the integer value corresponding to the specified day of the week. Syntax: weekday() Parameters: This function does not accept any parameter. Return values: This function returns the integer mapping corresponding to the specified day of the week. Below table shows the integer values cor
3 min read
Convert Python datetime to epoch
In this article, we are going to discuss various ways by which we can convert Python DateTime to epoch. The epoch time is also known as POSIX time which will indicate the number of seconds passed from January 1, 1970, 00:00:00 (UTC) in most Windows and Unix systems. Note: Epoch is platform-dependent which means it depends on the system or operating
4 min read
Python datetime.timetz() Method with Example
The timetz() function manipulates the objects of the DateTime class of the DateTime module. This function uses an instance method given to it via reference, and converts them, and returns a time object with the same hour, minute, second, microsecond, and fold and tzinfo attributes. Syntax: timetz() Parameters: This function does not accept any para
3 min read
replace() Function Of Datetime.date Class In Python
replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters: Year: New year value (range: 1 <= year <= 9999)month: New month value(range: 1 <= mont
2 min read
Article Tags :
Practice Tags :