The Wayback Machine - https://web.archive.org/web/20240822060458/https://www.geeksforgeeks.org/working-with-datetime-objects-and-timezones-in-python/
Open In App

Working with Datetime Objects and Timezones in Python

Last Updated : 25 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 object

Method 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/object of the datetime.datetime class. The now() method returns an object that represents the current date and time.

Python




# importing datetime module
import datetime
 
# getting the datetime object
# of current date and time
print(datetime.datetime.now())


Output:

2022-01-17 17:15:50.838373

Method 2: Defining the Datetime object manually

We can also declare the DateTime object manually

Python




# importing datetime module
import datetime
 
# initialising the datetime object
obj = datetime.datetime(2001, 12, 9)
print(obj)


Output:

2001-12-09 00:00:00

After this, we learn how to format our Datetime objects.

Formatting DateTime objects

Sometimes we need to print our datetime objects in different formats. For these operations, we are going to use strftime() method. The syntax of strftime() is:

Syntax : strftime(format)

Python




# importing datetime object
import datetime
 
# initialising datetime object
obj = datetime.datetime(2001, 12, 9)
 
# Example 1
print(obj.strftime("%a %m %y"))
 
# Example 2
print(obj.strftime("%m-%d-%Y %T:%M%p"))


Output:

Sun 12 01
12-09-2001 00:00:00:00AM

We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.

Python




# importing datetime object
import datetime
 
# initialising datetime object
obj = datetime.datetime(2001, 12, 9, 12, 11, 23)
 
# Hours
print(obj.hour)
 
# Minutes
print(obj.minute)
 
# Seconds
print(obj.second)


Output:

12
11
23

We can also get a datetime object using the strptime() method, in which we get a DateTime object from a string. Since the strings we use can be formatted in any form, we need to specify the expected format. To understand this, let’s look at the syntax of strptime():

Syntax : datetime.strptime(data,expected_format)

Parameters : 

  • data : Our time and date passed as a string in a particular format
  • expected_format : the format in which data is presented in the first parameter

Python




# importing datetime object
import datetime
 
# using strptime() method
print(datetime.datetime.strptime("Jan 1, 2013 12:30 PM",
                                 "%b %d, %Y %I:%M %p"))


Output:

2013-01-01 12:30:00

Working with Timezones

The DateTime objects that we have been working with till now are what are known as naive DateTime objects. A naive DateTime object does not have any information on the timezone. We can check this using the tzinfo property.

Python




# importing datetime object
import datetime
 
# defining the object
obj = datetime.datetime(2001, 11, 15, 1, 20, 25)
 
# checking timezone information
print(obj.tzinfo)


Output:

None

To set our own timezones, we have to start using the pytz module. In the next example, we will create a DateTime object first and then create a timezone object. We will then localize that timezone object to the DateTime object and check the tzinfo property.

Python




# importing datetime and pytz
import datetime
import pytz
 
# defining the object
obj = datetime.datetime(2001, 11, 15, 1, 20, 25)
 
# defining the timezone
tz = pytz.timezone('Asia/Kolkata')
 
# localising the datetime object
# to the timezone
aware_obj = tz.localize(obj)
 
# checking timezone information
print(aware_obj.tzinfo)


Output : 

Asia/Kolkata

Conversion of DateTime object from one Timezone to another

To convert the DateTime object from one timezone to another we need to use the astimezone() method. 

Syntax : DateTimeObject.astimezone(tz=None)

tz : The specified timezone to which the DateTimeObject needs to be converted to

Returns :  a datetime instance according to the specified time zone parameter tz

Python




# importing datetime and pytz
import datetime
import pytz
 
# defining the object and localising it to a timezone
obj = datetime.datetime(2001, 11, 15, 1, 20, 25)
tz = pytz.timezone('Asia/Kolkata')
obj = tz.localize(obj)
 
# Creating a new timezone
new_tz = pytz.timezone('America/New_York')
 
# Changing the timezone of our object
new_tz_time = obj.astimezone(new_tz)
 
# Printing out new time
print(new_tz_time)


Output:

2001-11-14 14:50:25-05:00 

Working with the timedelta class

We can check the difference between two DateTime objects with are either both localized to the same timezone or are naive. In the next example, we are going to create two DateTime objects localized to the same timezone and check their difference. The difference of the time returned should be an object of the timedelta class.

Python




# importing datetime and pytz
import datetime
import pytz
 
# defining the objects
obj1 = datetime.datetime(2001, 11, 15, 1, 20, 25)
obj2 = datetime.datetime(2001, 6, 3, 2, 10, 12)
 
# Defining the timezone
tz = pytz.timezone('Asia/Kolkata')
 
# localising the objects to the timezone
obj1 = tz.localize(obj1)
obj2 = tz.localize(obj2)
 
# printing the differences
print(obj2-obj1)
print(obj1-obj2)
 
# Checking the object type of the
# difference returned
print(type(obj1-obj2))


Output : 

-165 days, 0:49:47
164 days, 23:10:13
<class 'datetime.timedelta'>

Not just differences, timedelta objects can also be used for addition. If we add a timedelta object to a datetime object, we get another datetime object that has the timedelta factored in as the difference with the first datetime object. Let’s see the example :

Python




# importing datetime and pytz
import datetime
import pytz
 
# defining the objects
obj = datetime.datetime(2001, 11, 15, 1, 20, 25)
 
# defining a timedelta
diff = datetime.timedelta(days=90, hours=1)
 
# getting a datetime object
# that is 90 days and 1 hour ahead
new_obj = obj+diff
 
# Our final answer
print(new_obj)


Output: 

2002-02-13 02:20:25


Similar Reads

How to convert date and time with different timezones in Python?
In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current tim
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
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
Pandas Series dt.to_pydatetime | Return Python DateTime Objects
Pandas dt.to_pydatetime() method returns the data as an array of native Python DateTime objects. Timezone information is retained if present. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.date | Extract Date From DateTime Objects
The dt.date attribute extracts the date part of the DateTime objects in a Pandas Series. It returns the NumPy array of Python datetime.date objects, mainly the date part of timestamps without information about the time and timezone. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '201
2 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 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
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
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
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 datetim
4 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
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
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
Article Tags :
Practice Tags :
three90RightbarBannerImg