Search code examples
pythondatetimetimezonepytzlocaltime

Converting other time zones into local time zone (offset)


I'm trying to make a function that would take two arguments as input.

  1. The time as a string ("2021-08-13 19:00")
  2. The time zone (-4)

I want the function to convert the time with the given time zone to my computer's local time zone (offset). Could anyone help out?


Solution

  • You can create a timezone object from the UTC offset hours via a timedelta object. Then use tzlocal to obtain the local time zone (i.e. the one your machine is configured to use) and convert using astimezone.

    Ex:

    from datetime import datetime, timedelta, timezone
    from tzlocal import get_localzone # pip install tzlocal
    
    def to_local(s, offsethours):
        """
        convert date/time string plus UTC offset hours to date/time in
        local time zone.
        """
        dt = datetime.fromisoformat(s).replace(tzinfo=timezone(timedelta(hours=offsethours)))
        # for Python < 3.7, use datetime.strptime(s, "%Y-%m-%d %H:%M") instead of datetime.fromisoformat(s)
        return dt.astimezone(get_localzone())
        
        
    time_string = "2021-08-13 19:00"
    time_offset = -4
    
    dt_local = to_local(time_string, time_offset)
    
    print(repr(dt_local))
    print(dt_local.isoformat())
    print(dt_local.utcoffset())
    # datetime.datetime(2021, 8, 14, 1, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
    # 2021-08-14T01:00:00+02:00
    # 2:00:00