python datetime timezone string code example

Example 1: datetime python timezone

import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))

Example 2: python datetime to string iso format

from datetime import datetime
some_date = datetime.now()
iso_date_string = some_date.isoformat()

# For older version of python 
iso_date_string = some_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z')

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