Search code examples
python-3.xdatetimeutcdata-conversion

Convert date and time from UTC to local in specifed format


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?


Solution

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