Get Timezone Aware Value from datetime today in Python (Example Code)
On this page, I’ll illustrate how to return the current time from a specific timezone in the Python programming language.
Preparing the Example
Before we start, we have to load the datetime module:
import datetime # Import datetime |
import datetime # Import datetime
To return the time of today in our current timezone location, we use the today() function:
x = datetime.datetime.today() # Return today print(x) # 2022-05-12 10:33:44.466331 |
x = datetime.datetime.today() # Return today print(x) # 2022-05-12 10:33:44.466331
Example: Using now() Function to Return datetime in Other Timezone
For showing the time in a different timezone, we first need to load the pytz library:
import pytz # Import pytz |
import pytz # Import pytz
Now we can apply the datetime.now() function and the pytz.timezone() function to show the time in a specific timezone (i.e. US/Pacific).
x_manual_tz = datetime.datetime.now(pytz.timezone('US/Pacific')) # Get other timezone print(x_manual_tz) # 2022-05-12 02:33:44.466331+00:00 |
x_manual_tz = datetime.datetime.now(pytz.timezone('US/Pacific')) # Get other timezone print(x_manual_tz) # 2022-05-12 02:33:44.466331+00:00
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)
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.