Home > Software engineering >  facing difficulties converting utc timezone to local
facing difficulties converting utc timezone to local

Time:04-05

I am getting date and time like this

date_time =  "2022-02-17 08:29:36.345374"

And to convert these to AM, PM format I am doing something like this

date_formate = datetime.fromisoformat(date_time).strftime('%d/%m/%Y %I:%M %p')

but End time I am getting is in not local time seems it's in UTC , I am trying to convert it in utc but no luck doing something like this

dtUTC = datetime.fromisoformat(date_formate[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))

got this solution on stackoverflow but getting error Invalid isoformat string: '2022-02-17 08:29:36.345374'

CodePudding user response:

Python assumes local time by default if you don't specify a time zone / UTC offset. So in this case, you need to set UTC first, then convert, then format (if you want a string as output):

from datetime import datetime, timezone

date_time =  "2022-02-17 08:29:36.345374" # UTC is not specified here...

local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone()
print(local) # my tz was on UTC 1 at that date...
# 2022-02-17 09:29:36.345374 01:00

local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM

If astimezone(None) does not work, you can try tzlocal;

import tzlocal
zone = tzlocal.get_localzone()
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM

or derive a timezone object from a timedelta, e.g.

from datetime import timedelta
zone = timezone(timedelta(minutes=-300)) # UTC-5 hours
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 03:29 AM
  • Related