pythondatetimetimezonelocaltimezoneinfo

Convert the same local time to UTC on different dates, respecting the local DST status


I have several local time points:

import datetime
from zoneinfo import ZoneInfo as zi

wmr = datetime.time(hour=12, tzinfo=zi("GMT"))
ecb = datetime.time(hour=14, minute=15, tzinfo=zi("CET"))
jpx = datetime.time(hour=14, tzinfo=zi("Japan"))

which I want to convert to UTC times given a date.

E.g.,

local2utc(datetime.datetime(2024,1,1), wmr) ---> "2024-01-01 12:00:00" 
local2utc(datetime.datetime(2024,6,1), wmr) ---> "2024-06-01 11:00:00" (DST active)
local2utc(datetime.datetime(2024,1,1), ecb) ---> "2024-01-01 13:15:00" 
local2utc(datetime.datetime(2024,6,1), ecb) ---> "2024-06-01 12:15:00" (DST active)
local2utc(datetime.datetime(2024,1,1), jpx) ---> "2024-01-01 05:00:00" 
local2utc(datetime.datetime(2024,6,1), jpx) ---> "2024-06-01 05:00:00" (no DST in Japan)

The following implementation

def local2utc(date, time):
    local_dt = datetime.datetime.combine(date,time)
    tm = local_dt.utctimetuple()
    return datetime.datetime(*tm[:7])

seems for work for Japan and CET, but not for GMT/WET (because London is on BST/WEST in the summer).

So, what do I do?


Solution

  • Python uses the IANA time zone database. The list of time zone names can be found here. According to this table, "GMT" is a time zone that has a 0 UTC offset and does not observe daylight saving.

    Perhaps "Europe/London" would give you the results you are looking for.