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

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

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

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

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