I have UTC date time as 2021-02-24 12:41:40
.
I want to get it converted into local timezone in 24 hour format ie "IST" in same format ie 2021-02-24 18:11:40
.
I referred many answers on Stackoverflow, but I am not able to get the result in desired format.
How can it be achieved in Python3?
what I linked applied specifically to your question:
from datetime import datetime, timezone
from dateutil.tz import gettz
# the given info:
ist = gettz("Asia/Kolkata")
s = "2021-02-24 12:41:40"
# now parse to datetime and set time zone UTC
dt = datetime.fromisoformat(s).replace(tzinfo=timezone.utc)
# convert to IST time zone
dt = dt.astimezone(ist)
# output to isoformat string, but without time zone info
s = dt.replace(tzinfo=None).isoformat(' ')
print(s)
# 2021-02-24 18:11:40
Solution for Python 3.6.*
datetime = "2021-02-24 12:41:40"
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = datetime.strptime( datetime,'%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
localTime = local.replace(tzinfo=None).isoformat(' ')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.