how to change timezone in python code example

Example 1: python time now other timezone

#as an aware datetime
from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time


#or from pytz database
import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

Example 2: convert timezone python

from datetime import datetime
from pytz import timezone, all_timezones

# aware dt-obj
dt_obj = datetime.strptime('2021-05-19T01:55:10+0000', '%Y-%m-%dT%H:%M:%S%z')
# double confirmaiton: aware dt-obj
dt_obj.tzinfo
# correct
dt_obj.astimezone(timezone('US/Pacific'))
# correct
dt_obj.replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific'))
# confirmation: desired tz
dt_obj.replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific')).tzinfo
# ~~~~~~~
# naive datetime object
datetime.utcnow()
# confirmation: naive dt-obj
print(datetime.utcnow().tzinfo)
# incorrect because started with naive datetime object
datetime.utcnow().astimezone(timezone('US/Pacific'))
# correct because add/replace tzinfo of initial dt-obj before conversion to desired tz
datetime.utcnow().replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific'))
# confirmation: aware dt-obj
datetime.utcnow().replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific')).tzinfo

# ~~~~~~~~~~~
# len(all_timezones) == 593
for tz in all_timezones:
    print(tz)