How to convert datetime to different timezone in Python using pytz

Posted by Vivek Shukla on Jun 20, 2023 under Python

Create datetime instance with timezone info

import datetime
import pytz
dt = datetime.datetime(2021, 1, 6, 0, 0, 0)
tz = pytz.timezone('Asia/Kolkata')
tzinfo_dt = tz.localize(dt)
tzinfo_dt

# output:
# datetime.datetime(2021, 1, 6, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

Note: Passing tzinfo in datetime is not recommended by pytz.

Convert datetime to different timezone

import datetime
import pytz

#creating timezone aware datetime instance
dt = pytz.utc.localize(datetime.datetime.now())
# converting to IST
ist_dt = dt.astimezone(pytz.timezone('Asia/Kolkata'))
ist_dt
# output:
# datetime.datetime(2021, 1, 6, 9, 28, 57, 974939, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

us_east = dt.astimezone(pytz.timezone('US/Eastern'))
# output:
# datetime.datetime(2021, 1, 5, 23, 1, 49, 588549, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>)
Built with  Svelte Starter Kit