You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you over-specify a datetime strptime string, it seems that datetime.strptime when encountering a component that has been specified twice, will overwrite earlier values with more recent ones.
One approach would be to ban over-specified formats, but that would be a problem for someone who wants to, use a format like "%M %B" (e.g. something sortable by month number while also showing month name), so I think we don't want to do that.
Alternatively we could start raising an exception if you get different values from these two things, or possibly a warning.
Or we can just accept that if you use a weird format you should expect weird behavior.
To avoid the issue where the last directive overwrites earlier values:
since more than one directive is needed, maybe split the string and parse the components manually (handling the split and parsing based on the length of the string)?
Maybe also apply custom logic to handle dynamic formats, especially if you encounter different scenarios with varying date formats.... (idk if your format is dynamic?)
defparse_date(input_str):
iflen(input_str) ==6: # 4-digit year followed by 2-digit yearfull_year=input_str[:4]
short_year=input_str[4:]
year_full=datetime.strptime(full_year, "%Y")
year_short=datetime.strptime(short_year, "%y")
returnyear_short.replace(year=year_full.year) # Use full year from the first parteliflen(input_str) ==4: # Only 4-digit yearreturndatetime.strptime(input_str, "%Y")
else:
raiseValueError("Invalid date format")
Activity
Mariatta commentedon Sep 26, 2024
I'd be ok with raising exception, seems like it's a user error for passing these kind of conflicting format specifiers.
We could also start documenting this case, saying that the latest format specifiers that appears will prevail.
Mariatta commentedon Oct 5, 2024
@pganssle I created a PR to document this weird behavior. I think it's still worth raising a warning though. #125009
alliesw commentedon Dec 17, 2024
To avoid the issue where the last directive overwrites earlier values:
since more than one directive is needed, maybe split the string and parse the components manually (handling the split and parsing based on the length of the string)?
Maybe also apply custom logic to handle dynamic formats, especially if you encounter different scenarios with varying date formats.... (idk if your format is dynamic?)
alliesw commentedon Dec 17, 2024
This is an example of what I'm getting at:
Example usage:
StanFromIreland commentedon Apr 14, 2025
This is a stdlib issue (
strptime.py) the extension-modules label can be removed.