convert datetime string with timezone to datetime python code example

Example: 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)