Make Unaware datetime Time Zone Aware in Python (Example)

 

In this post, I’ll show how to make an unaware datetime time zone aware in the Python programming language.

This article contains the sections below:

Now, let’s get started!

 

Import Modules & Create Data

As a first step, we have to import two modules to Python: datetime and pytz.

import datetime
import pytz

Next, we have to create an exemplifying datetime object:

my_datetime_unaware = datetime.datetime(2021, 5, 25, 11, 12, 2, 0)
print(my_datetime_unaware)
# 2021-05-25 11:12:02

As you can see, we have created a datetime object without an explicitly shown time zone.

 

Example : Display Time Using pytz.utc.localize()

This example illustrates how to properly display a time zone of a datetime object.

For this task, we can use the replace function and the tzinfo parameter as shown below:

my_datetime_aware = my_datetime_unaware.replace(tzinfo = pytz.UTC)
print(my_datetime_aware)
# 2021-05-25 11:12:02+00:00

As you can see, we have created a new data object containing the corresponding time zone.

 

Video, Further Resources & Summary

If you need more explanations on how to make unaware datetime timezone aware in Python, you can have a look at the following video of the YouTube channel of Gen Grievous.

In the video, the speaker explains working with datetime objects, dates, times, and pytz time zones.

 

 

In addition to the video, you could have a look at the other tutorials on Statistics Globe:

This post has shown how to make unaware datetime timezone aware in the Python programming language. In case you have further questions, you may leave a comment below.

 

Gottumukkala Sravan Kumar Statistician & Programmer

Note: This article was created in collaboration with Gottumukkala Sravan Kumar. You may find more information about Gottumukkala and his other articles on his profile page.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top