How to Make an Unaware datetime Time Zone Aware (Python Example)

This article explains how to make an unaware datetime time zone aware in Python.

Creating Example Data & Loading Modules

Before we can start, we have to load the modules datetime and pytz to Python:

import datetime
import pytz

Then we can create a datetime object as example data:

datetime_x_unaware = datetime.datetime(2022, 4, 18, 16, 20, 4, 0)
print(datetime_x_unaware)
# 2022-04-18 16:20:04

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

To display a time zone of a datetime object properly, we can use the replace function combined with the tzinfo parameter:

datetime_x_aware = datetime_x_unaware.replace(tzinfo = pytz.UTC)
print(datetime_x_aware)
# 2022-04-18 16:20:04+00:00

A new data object containing the corresponding time zone has been created.

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top