Set datetime Object to Local Time Zone in Python (Example)
This post explains how to transform a datetime object to the local time zone in Python.
Creating Example Data & Loading datetime Module
First, we have to load the datetime module, as you can see below:
from datetime import datetime |
from datetime import datetime
Additionally, the pytz module has to be imported.
import pytz |
import pytz
Now, we generate a datetime object using the following code:
date_x = datetime(2023, 3, 20, 18, 12, 55, tzinfo = pytz.utc) print(date_x) # 2023-03-20 18:12:55+00:00 |
date_x = datetime(2023, 3, 20, 18, 12, 55, tzinfo = pytz.utc) print(date_x) # 2023-03-20 18:12:55+00:00
To display the time zone that is used for this datetime object we can use the strftime() function.
date_x_utc = date_x.strftime('%Y-%m-%d %H:%M:%S %Z%z') print(date_x_utc) # 2023-03-20 18:12:55 UTC+0000 |
date_x_utc = date_x.strftime('%Y-%m-%d %H:%M:%S %Z%z') print(date_x_utc) # 2023-03-20 18:12:55 UTC+0000
The output shows the time zone of our datetime object: UTC time zone (Coordinated Universal Time)
Example: Using astimezone() Function to Convert datetime Object
To convert our datetime object into local time, we can use the astimezone() function:
import datetime local_time = datetime.datetime.now().astimezone().tzinfo print(local_time) |
import datetime local_time = datetime.datetime.now().astimezone().tzinfo print(local_time)
You can see my local time zone is CET (i.e. Central European Time).
To transform the example datetime object to CET, we can use the following code:
date_x_cet = date_x.astimezone(pytz.timezone('Europe/Berlin')).strftime('%Y-%m-%d %H:%M:%S %Z%z') print(date_x_cet) # 2023-03-20 19:12:55 CET+0100 |
date_x_cet = date_x.astimezone(pytz.timezone('Europe/Berlin')).strftime('%Y-%m-%d %H:%M:%S %Z%z') print(date_x_cet) # 2023-03-20 19:12:55 CET+0100
The Central European Time (CET) zone is one hour earlier than Coordinated Universal Time (UTC) zone.
Further Resources
Please find some related tutorials below.
- Set datetime to Different Time Zone in Python (3 Examples)
- How to Make an Unaware datetime Time Zone Aware (Python Example)
- Set datetime Object to Date Only String in Python (3 Examples)
- Set Epoch Time to datetime Object & Vice Versa in Python (2 Examples)
- 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.