Working with Datetime Objects and Timezones in Python
Last Updated :
25 Mar, 2022
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
Python | Working with date and time using Pandas
While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data. Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Let's try to understand with the examples discussed b
8 min read
How to make a timezone aware datetime object in Python
A naive datetime in Python contains only the date and time, while a timezone-aware datetime includes timezone details, such as the UTC offset or timezone name, allowing it to accurately represent an exact moment in time. Creating a timezone-aware datetime means adding this timezone information to a
3 min read
Add Years to datetime Object in Python
In this article let's learn how to add years to a datetime object in python. Python Datetime module supplies classes datetime. These classes provide us with a number of functions to deal with dates, times, and time intervals. Date and datetime are an object in Python, so when you manipulate them, y
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 d
4 min read
How to add time onto a DateTime object in Python
In Python, adding time (such as hours, minutes, seconds, or days) to a datetime object is commonly done using the timedelta class from the datetime module. This allows precise manipulation of date and time values, including performing arithmetic operations on datetime objects. It's key features incl
3 min read
Working with Date and Time in Julia
Julia provides a library to use Dates for dealing with date and time. The Dates module comes inbuilt with the Julia we just need to import it in order to use it. Now we need to prefix every function with an explicit type Dates, e.g Dates.Date. If you donât want to prefix on each function just add us
5 min read
Working With Dates in Python
In this article, we will discuss how to work with dates using python. Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed. By
4 min read
Add Months to datetime Object in Python
In this article, let's delve into the techniques for Add Months to datetime Object in Python. Working with dates and times often requires manipulation and adjustment, and understanding how to add months to a datetime object is a crucial skill. We will explore various methods and libraries to achieve
3 min read
Convert string to datetime in Python with timezone
Prerequisite: Datetime module In this article, we will learn how to get datetime object from time string using Python. To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. Syntax : datetime.strptime(date_strin
3 min read
Python - Timedelta object with negative values
In Python, there is the Datetime library which is the in-built library under which timedelta() function is present. Using this function we can find out the future date and time or past date and time. In timedelta() object delta represents the difference between two dates or times. Syntax: datetime.t
5 min read