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
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.