How Do I Change Timezone Of datetime.datetime Object?

I’m running schedule tasks, and the code checks the server using datetime.now() to run the tasks. However, timezone is set to UTC , which is leading to false positives to my code (Python). How do I change timezone?

2 Likes

Welcome to the forums, @underweb2009!
If, for example, you wanted to turn the UTC time into PST, you would add 8 hours to the UTC time. You can do this by running this code:

utc_to_pst = datetime.datetime.now() + datetime.timedelta(hours=8)

And replace hours with how ever many hours UTC is ahead of your preferred timezone.

4 Likes
now_utc = datetime.datetime.now(pytz.UTC)
est_tz = pytz.timezone('EST')
timestamp = now_utc.astimezone(est_tz)

This will get the time for EST, simply replace EST in pytz.timezone(‘EST’) with the time zone you want.

You will also need to import pytz though.

import datetime
import pytz

now_utc = datetime.datetime.now(pytz.UTC)
virginia_tz = pytz.timezone('America/New_York')
timestamp = now_utc.astimezone(virginia_tz)

print(timestamp)

3 Likes