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
import datetime
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
import datetime
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
import datetime
obj = datetime.datetime( 2001 , 12 , 9 )
print (obj.strftime( "%a %m %y" ))
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
import datetime
obj = datetime.datetime( 2001 , 12 , 9 , 12 , 11 , 23 )
print (obj.hour)
print (obj.minute)
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
import datetime
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
import datetime
obj = datetime.datetime( 2001 , 11 , 15 , 1 , 20 , 25 )
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
import datetime
import pytz
obj = datetime.datetime( 2001 , 11 , 15 , 1 , 20 , 25 )
tz = pytz.timezone( 'Asia/Kolkata' )
aware_obj = tz.localize(obj)
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
import datetime
import pytz
obj = datetime.datetime( 2001 , 11 , 15 , 1 , 20 , 25 )
tz = pytz.timezone( 'Asia/Kolkata' )
obj = tz.localize(obj)
new_tz = pytz.timezone( 'America/New_York' )
new_tz_time = obj.astimezone(new_tz)
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
import datetime
import pytz
obj1 = datetime.datetime( 2001 , 11 , 15 , 1 , 20 , 25 )
obj2 = datetime.datetime( 2001 , 6 , 3 , 2 , 10 , 12 )
tz = pytz.timezone( 'Asia/Kolkata' )
obj1 = tz.localize(obj1)
obj2 = tz.localize(obj2)
print (obj2 - obj1)
print (obj1 - obj2)
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
import datetime
import pytz
obj = datetime.datetime( 2001 , 11 , 15 , 1 , 20 , 25 )
diff = datetime.timedelta(days = 90 , hours = 1 )
new_obj = obj + diff
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
In this example, we are going to see how to make a timezone-aware DateTime object in Python. Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is
4 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, yo
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 this article, we will discuss the addition of time onto a specified DateTime object in Python. The effect of this will produce a new DateTime object. This addition can be performed by using datetime.timedelta() function. The timedelta() function is used for calculating differences in dates and al
2 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_string
3 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:
2 min read