Search code examples
pythondatetimetimeutc

How to convert local time to UTC, considering daylight saving time?


I have datetime values in local time zone, and I need to convert them into UTC. How can I do this conversion for historical records, considering daylight saving time in the past?

Local               UTC
2018/07/20 09:00    ???
2018/12/31 11:00    ???
2019/01/17 13:00    ???
2020/08/15 18:00    ???

This is what I have so far:

import pytz
without_timezone = datetime(2018, 7, 20, 9, 0, 0, 0)
timezone = pytz.timezone("Europe/Vienna")
with_timezone = timezone.localize(without_timezone)
with_timezone

So, I assigned Europe/Vienna to all records (I assume that this considers daylight saving time, right?)

Now I need to convert it into UTC...


Solution

  • Assuming Local contains date/time as observed locally, i.e. including DST active/inactive, you would convert to datetime object, set time zone, and convert to UTC.

    Ex:

    from datetime import datetime, timezone
    from zoneinfo import ZoneInfo # Python 3.9
    
    Local = ["2018/07/20 09:00", "2018/12/31 11:00", "2019/01/17 13:00", "2020/08/15 18:00"]
    
    # to datetime object and set time zone
    LocalZone = ZoneInfo("Europe/Vienna")
    Local = [datetime.strptime(s, "%Y/%m/%d %H:%M").replace(tzinfo=LocalZone) for s in Local]
    
    for dt in Local:
        print(dt.isoformat(" "))
    # 2018-07-20 09:00:00+02:00
    # 2018-12-31 11:00:00+01:00
    # 2019-01-17 13:00:00+01:00
    # 2020-08-15 18:00:00+02:00
    
    # to UTC
    UTC = [dt.astimezone(timezone.utc) for dt in Local]
    
    for dt in UTC:
        print(dt.isoformat(" "))
    # 2018-07-20 07:00:00+00:00
    # 2018-12-31 10:00:00+00:00
    # 2019-01-17 12:00:00+00:00
    # 2020-08-15 16:00:00+00:00
    

    Note: with Python 3.9, you don't need third party libraries for time zone handling in Python anymore. There is a deprecation shim for pytz.