Thursday, December 26, 2024
Google search engine
HomeLanguagesWorking with Datetime Objects and Timezones in Python

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

RELATED ARTICLES

Most Popular

Recent Comments