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 |
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 |
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 |
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.
- Set datetime to Different Time Zone in Python (3 Examples)
- Set datetime Object to Local Time Zone in Python (Example)
- Set Epoch Time to datetime Object & Vice Versa in Python (2 Examples)
- Set Unix Timestamp to datetime in Python (Example)
- All Python Programming Tutorials
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.