Home > database >  Python get timezone from offset string
Python get timezone from offset string

Time:05-23

I'm new to datetime in Python and I have a date string in this format '05/18/2022 12:00:55'. And a separate offset string like this '-06:00'. I'm trying to make a final datetime object which is timezone aware based on the offset string. Expected Result 2022-05-18 06:00:55-06:00

Try 1 - Add the offset string to the datetime string and convert to datetime object. this results in 2022-05-18 12:00:55-06:00 and not 2022-05-18 06:00:55-06:00

date_string = '05/18/2022 12:00:55'
timezone_string = '-06:00'
date_string_2 = datetime.strptime(date_string   timezone_string, '%m/%d/%Y %H:%M:%S%z')
print(date_string_2)

Try 2 - Play around with the tzinfo property but this throws an error

date_string = '05/18/2022 12:00:55'
timezone_string = '-06:00'
date_string_2 = datetime.strptime(date_string, '%m/%d/%Y %H:%M:%S%z')
date_string_2.replace(tzinfo=timezone_string)
print(date_string_2)

Could anybody please help and/or point me in the right direction with this. Thank you.

CodePudding user response:

Basically you'll want to parse the date_string to datetime object, replace tzinfo with UTC, then convert with astimezone to UTC-6. For that, you parse timezone_string to datetime object as well, but just use its tzinfo.

EX:

from datetime import datetime, timezone

date_string = "05/18/2022 12:00:55"
timezone_string = "-06:00"

dtobj_utc = datetime.strptime(date_string, "%m/%d/%Y %H:%M:%S").replace(tzinfo=timezone.utc)
dtobj_tz = dtobj_utc.astimezone(datetime.strptime(timezone_string, "%z").tzinfo)

print(dtobj_tz.isoformat(" ", timespec="seconds"))
# 2022-05-18 06:00:55-06:00
  • Related