0

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 i.e. "IST" in same format i.e. 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?

1

2 Answers 2

2

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 tzinfo to 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 
Sign up to request clarification or add additional context in comments.

1 Comment

This might work for Python 3.7* becuase I got AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'. Thank you for response though, posting answer for Python 3.6.*
1

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(' ') 

1 Comment

Good point there using tzlocal(). With Python 3.6 you should also be able to use astimezone(None), see e.g. stackoverflow.com/a/62334092/10197418

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.