python convert to timezone code example
Example 1: how to convert time from one timezone to another in python
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))
Example 2: convert timezone python
from datetime import datetime
from pytz import timezone, all_timezones
dt_obj = datetime.strptime('2021-05-19T01:55:10+0000', '%Y-%m-%dT%H:%M:%S%z')
dt_obj.tzinfo
dt_obj.astimezone(timezone('US/Pacific'))
dt_obj.replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific'))
dt_obj.replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific')).tzinfo
datetime.utcnow()
print(datetime.utcnow().tzinfo)
datetime.utcnow().astimezone(timezone('US/Pacific'))
datetime.utcnow().replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific'))
datetime.utcnow().replace(tzinfo=timezone('UTC')).astimezone(timezone('US/Pacific')).tzinfo
for tz in all_timezones:
print(tz)
Example 3: how to convert time from one timezone to another in python
$ pip install pytz