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?

Tech Girl
  • 169
  • 2
  • 17
  • see e.g. https://stackoverflow.com/a/63628816/10197418 - you can parse your string with [datetime.fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) – FObersteiner Feb 24 '21 at 13:22

2 Answers2

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 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.* – Tech Girl Feb 25 '21 at 11:55
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(' ')
Tech Girl
  • 169
  • 2
  • 17
  • 1
    Good point there using `tzlocal()`. With Python 3.6 you should also be able to use `astimezone(None)`, see e.g. https://stackoverflow.com/a/62334092/10197418 – FObersteiner Feb 25 '21 at 12:06