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 = "2021-08-05 10:03:24.585Z"

datetime_object = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%fZ')

local_tz = timezone('Asia/Kolkata')
start_date = local_tz.localize(datetime_object)
print(start_date.replace(tzinfo=local_tz))

But Still the output is not with the timezone I have mentioned how can I convert the time and print the time from the time.

Output:

2021-08-05 10:03:24.585000+05:21
4

3 Answers

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 ZoneInfo
from 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.

5

You can use sth like this:

from datetime import datetime
from dateutil import tz

from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Kolkata')

utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

utc = utc.replace(tzinfo=from_zone)

central = utc.astimezone(to_zone)
0

For Python 3.7+

from datetime import datetime
st = "2021-08-05 10:03:24.585Z"
dtUTC = datetime.fromisoformat(st[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest