Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading