pythontimezoneutcpython-datetime

How can I parse a date time string with the 'WET' timezone


I am trying to parse a date string like this:

import datetime

document_updated_on = '01-Feb-2024#15:22 WET'
format_str = "%d-%b-%Y#%H:%M %Z"
updated_on_date = datetime.datetime.strptime(document_updated_on, format_str)

I am having issues with the time zone and getting the error:

ValueError: time data '01-Feb-2024#15:22 WET' does not match format '%d-%b-%Y#%H:%M %Z'


Solution

  • The %Z specifier is deprecated anyway, and WET (Western European Time) simply doesn't seem to be supported.

    You can work around this with something like

    import datetime
    from zoneinfo import ZoneInfo
    
    
    def parse_datetime(dt_str: str):
        if dt_str.endswith(" WET"):
            dt = datetime.datetime.strptime(dt_str.removesuffix(" WET"), "%d-%b-%Y#%H:%M")
            return dt.replace(tzinfo=ZoneInfo("WET"))
        return datetime.datetime.strptime(dt_str, "%d-%b-%Y#%H:%M %Z")
    
    
    print(parse_datetime('01-Feb-2024#15:22 WET').timetuple())
    print(parse_datetime('01-Feb-2024#15:22 EEST').timetuple())
    

    This prints out

    time.struct_time(tm_year=2024, tm_mon=2, tm_mday=1, tm_hour=15, tm_min=22, tm_sec=0, tm_wday=3, tm_yday=32, tm_isdst=0)
    time.struct_time(tm_year=2024, tm_mon=2, tm_mday=1, tm_hour=15, tm_min=22, tm_sec=0, tm_wday=3, tm_yday=32, tm_isdst=-1)