0

I have a string date which already contains an appropriate time zone offset -08:00 and I can convert it into a datetime variable but with UTC time zone format:

from datetime import datetime
from pytz import timezone
import pytz

str_date = '2020-01-01T00:00:00-08:00'#
specific_date_format = "%Y-%m-%d %H:%M:%S %Z"

my_date = datetime.fromisoformat(str_date)
print(my_date.strftime(specific_date_format))

_____________________________________________
Output
>> 2020-01-01 00:00:00 UTC-08:00

Format I need is

2020-01-01 00:00:00 PST

Not sure how to convert UTC-08:00 into PST.

Tried with pytz and saw suggestions to replace time zone with predefined 'America/Los_Angeles', but I need the code to detect that the hour offset UTC-08:00 corresponds to 'America/Los_Angeles' time zone and convert it as such.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
wavemonger
  • 71
  • 8
  • which python version? do you *have* have to use pytz? – FObersteiner Jan 10 '22 at 20:23
  • Version: Python 3.8.8 & pytz would be ideal, but other standard python libraries would work as well. Thanks in advance, @MrFuppes! – wavemonger Jan 10 '22 at 20:26
  • 2
    Note that UTC offsets can correspond to multiple time zones, so an unambiguous mapping of UTC offset to time zone is not possible in general. You'll have to *define* the mapping, e.g. 8 hours behind UTC corresponds to America/LA. – FObersteiner Jan 10 '22 at 20:38

1 Answers1

1

since your input already contains a UTC offset, you can parse the iso-format string to aware datetime (tzinfo set) and use astimezone to set the correct time zone. Using pytz:

from datetime import datetime
from pytz import timezone # Python 3.9: zoneinfo (standard lib)

str_date = '2020-01-01T00:00:00-08:00'

# to datetime
dt = datetime.fromisoformat(str_date)

# to tz
dt_tz = dt.astimezone(timezone("America/Los_Angeles"))

print(dt_tz)
# 2020-01-01 00:00:00-08:00
print(repr(dt_tz))
# datetime.datetime(2020, 1, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
print(dt_tz.strftime("%a, %d %b %Y %H:%M:%S %Z"))
# Wed, 01 Jan 2020 00:00:00 PST

See also: Display the time in a different time zone - e.g. this answer for a Python 3.9/zoneinfo example.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72