I'm trying to parse time using strptime
:
t = datetime.strptime('2024-08-21T11:00:00 EDT', '%Y-%m-%dT%H:%M:%S %Z')
This code works for me in GMT+4, but it fails in GMT-9:
ValueError: time data '2024-08-21T11:00:00 EDT' does not match format '%Y-%m-%dT%H:%M:%S %Z'
What am I doing wrong?
According to python docs strptime() only accepts certain values for %Z
strptime() only accepts certain values for %Z: any value in time.tzname for your machine’s locale the hard-coded values UTC and GMT
So someone living in Japan may have JST, UTC, and GMT as valid values, but probably not EST. It will raise ValueError for invalid values.
Testing locally
TZ="+4" python3 -c "import time; print(time.tzname)"
TZ="+4" python3 -c "import datetime; print(datetime.datetime.strptime('2024-08-21T11:00:00 EDT', '%Y-%m-%dT%H:%M:%S %Z'))"
Results
('', '')
ValueError: unconverted data remains: EDT
For a supported TZ
TZ="US/Eastern" python3 -c "import time; print(time.tzname)"
('EST', 'EDT')
TZ="US/Eastern" python3 -c "import datetime; print(datetime.datetime.strptime('2024-08-21T11:00:00 EDT', '%Y-%m-%dT%H:%M:%S %Z'))"
2024-08-21 11:00:00
Even error string changes for some TZ. America/Los_Angeles
returns error as reported by OP.
TZ="America/Los_Angeles" python3 -c "import datetime; print(datetime.datetime.strptime('2024-08-21T11:00:00 EDT', '%Y-%m-%dT%H:%M:%S %Z'))"
ValueError: time data '2024-08-21T11:00:00 EDT' does not match format '%Y-%m-%dT%H:%M:%S %Z'
Fails anyway even if tzname has values
TZ="America/Los_Angeles" python3 -c "import time; print(time.tzname)"
('PST', 'PDT')