Search code examples
pythondatetimetimezoneutcpytz

Convert a date with UTC timezone offset to corresponding local timezone format


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.


Solution

  • 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.