Working with Datetime Objects and Timezones in Python
Python provides tools for managing date and time using the datetime module. Whether you're fetching the current time, formatting it, handling timezones or calculating time differences, this module makes it simple. For example, you can easily convert "2001-11-15 01:20:25" from Asia/Kolkata to America/New_York or add 90 days to the current time using a timedelta.
Let’s go through the most useful operations when working with datetime and timezones.
Getting a Datetime object
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.
import datetime
# getting the datetime object of current date and time
print(datetime.datetime.now())
Output
2025-06-17 12:32:58.612718
Explanation:
- datetime.datetime.now() returns the current date and time with microseconds.
- The output includes year, month, day, hour, minute, second, and microsecond.
2. Defining the Datetime object manually
We can also declare the DateTime object manually
import datetime
# initialising the datetime object
obj = datetime.datetime(2001, 12, 9)
print(obj)
Output
2001-12-09 00:00:00
Explanation:
- You manually create a datetime for 9th December 2001.
- Time defaults to midnight if not specified.
After this, we learn how to format our Datetime objects.
Formatting Datetime Objects with strftime()
For printing our datetime objects in different formats, we use strftime() method. The syntax of strftime() is:
strftime(format)
import datetime
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
Explanation:
- strftime() converts a datetime object into a formatted string.
- %a = short weekday name, %m = month, %y = two-digit year.
- %T = full time (HH:MM:SS), %p = AM/PM.
Extracting Hour, Minute, and Second
We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.
import datetime
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
Explanation: You can access time components directly using attributes like .hour, .minute, and .second.
Creating Datetime from String Using strptime()
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
import datetime
dt = datetime.datetime.strptime("Jan 1, 2013 12:30 PM", "%b %d, %Y %I:%M %p")
print(dt)
Output
2013-01-01 12:30:00
Explanation:
- strptime() parses the string according to the given format.
- %b = month abbreviation, %I = hour (12-hour), %p = AM/PM.
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.
import datetime
obj = datetime.datetime(2001, 11, 15, 1, 20, 25)
# checking timezone information
print(obj.tzinfo)
Output
None
Explanation:
- The datetime object is naive and doesn't contain any timezone data.
- .tzinfo returns None for naive datetimes.
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.
import datetime
import pytz
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
Explanation:
- pytz.timezone() defines a timezone object.
- .localize() makes the naive datetime timezone-aware.
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)
where:
- 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
import datetime
import pytz
# defining the object and localising it to a timezone
dt = datetime.datetime(2001, 11, 15, 1, 20, 25)
tz = pytz.timezone('Asia/Kolkata')
dt = tz.localize(dt)
# Creating a new timezone
new_tz = pytz.timezone('America/New_York')
# Changing the timezone of our object
converted = dt.astimezone(new_tz)
# Printing out new time
print(converted)
Output
2001-11-14 14:50:25-05:00
Explanation:
- astimezone() converts a datetime object to another timezone.
- The converted object reflects the time in America/New_York with offset.