Search code examples
pythonpython-3.xdatetimestrptime

Is there a way to change the threshold for strptime()?


Python's strptime() function converts all the dates with year less than 69 (in format dd-mm-yy) to 20XX and above that to 19XX.

Is there any way to tweak this setting, noting found in docs.

datetime.strptime('31-07-68', '%d-%m-%y').date()

datetime.date(2068, 7, 31)

datetime.strptime('31-07-68', '%d-%m-%y').date()

datetime.date(1969, 7, 31)


Solution

  • Almost certainly your answer: Not without a Python patch.

    From line 375 in CPython _strptime.py:

    if group_key == 'y':
        year = int(found_dict['y'])
        # Open Group specification for strptime() states that a %y
        #value in the range of [00, 68] is in the century 2000, while
        #[69,99] is in the century 1900
        if year <= 68:
            year += 2000
        else:
            year += 1900
    

    https://github.com/python/cpython/blob/master/Lib/_strptime.py

    You could simulate an alternative by doing your own YY to YYYY conversion before invoking strptime.

    Technical caveat answer: Python being an interpreted language where modules are imported in a well understood way, you can technically manipulate the _strptime object at initialization runtime and replace with your own function, perhaps one decorating the original.

    You would need an extremely good reason to do this in production code. I did it once with another core library to work around an OS bug, in discussion with the team on when it would need to be removed. It's highly unintuitive to any future maintainer of your code, 9999/10000 times it will be better to just call some utility library in your own code. If you really need to do it, it's easy enough to work out, so I will skip the code sample to avoid copy/pasters.