[issue26460] datetime.strptime without a year fails on Feb 29
Nick Moore added the comment: I suspect this is going to come up about this time of every leap year :-/ The workaround is prepending "%Y " to the pattern and eg: "2020 " to the date string, but that's not very nice. Would adding a kwarg "default_year" be an acceptable solution? I can't think of any other situation other than leap years when this is going to come up. If both "default_year" and "%Y" are present throw an exception (maybe therefore just call the kwarg "year") In the weird case where you want to do date maths involving the month as well, you can always use a safe choice like "default_year=2020" and then fix the year up afterwards: ``` dt = datetime.strptime(date_str, "%b %d", default_year=2020) dt = dt.replace(year=2021 if dt.month > 6 else 2022) ``` -- nosy: +nickzoic versions: +Python 3.7, Python 3.8 ___ Python tracker <https://bugs.python.org/issue26460> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue26460] datetime.strptime without a year fails on Feb 29
Nick Moore added the comment: Not disagreeing with you that "%b %d" timestamps with no "%Y" are excerable, but they're fairly common in the *nix world unfortunately. People need to parse them, and the simple and obvious way to do this breaks every four years. I like the idea of having a warning for not including %Y *and* not setting a default_year kwarg though. -- ___ Python tracker <https://bugs.python.org/issue26460> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue26460] datetime.strptime without a year fails on Feb 29
Nick Moore added the comment: It's kind of funny that there's already consideration of this in _strptime._strptime(), which returns a tuple used by datetime.datetime.strptime() to construct the new datetime. Search for `leap_year_fix`. I think the concern though is if we changed the default year that might possibly break someone's existing code: thus my suggestion to allow the programmer to explicitly change the default. However, I can also see that if their code is parsing dates in this way it is already wrong, and that if we're causing users pain now when they upgrade Python we're at least saving them pain at 2024-02-29 00:00:01. Taking that approach, perhaps parsing dates with no year should just throw an exception, forcing the programmer to do it right the first time. In this case though, I'd rather have a "year" kwarg to prevent the programmer having to do horrible string hacks like my code currently does. I'm not sure: is it useful for me to produce a PR so we have something specific to consider? -- ___ Python tracker <https://bugs.python.org/issue26460> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com