pythonstrptime2-digit-year

2 digit years using strptime() is not able to parse birthdays very well


Consider the following birthdays (as dob):

When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield:

Well of course they’re supposed to be born in the same decade but now it’s not even in the same century!

According to the docs this is perfectly valid behaviour:

When 2-digit years are accepted, they are converted according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and values 0–68 are mapped to 2000–2068.

I understand why the function is set up like this but is there a way to work around this? Perhaps with defining your own ranges for 2-digit years?


Solution

  • If you're always using it for birthdays, just subtract 100 if the year is after now:

    if d > datetime.now():
        d = datetime(d.year - 100, d.month, d.day)