How Can I Convert From Utc Time To Local Time In Python?
So, I want to convert UTC date time 2021-08-05 10:03:24.585Z to Indian date time how to convert it? What I tried is from datetime import datetime from pytz import timezone st = '
Solution 1:
parse the date/time string to UTC datetime correctly and use astimezone instead of replace
to convert to a certain time zone (option for newer Python version (3.9+) in comments):
from datetime import datetime
# from zoneinfo import ZoneInfofrom dateutil.tz import gettz
st = "2021-08-05 10:03:24.585Z"
zone = "Asia/Kolkata"# dtUTC = datetime.fromisoformat(st.replace('Z', '+00:00'))
dtUTC = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%f%z')
# dtZone = dtUTC.astimezone(ZoneInfo(zone))
dtZone = dtUTC.astimezone(gettz(zone))
print(dtZone.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30
If you just need local time, i.e. your machine's setting, you can use astimezone(None)
as well.
Post a Comment for "How Can I Convert From Utc Time To Local Time In Python?"