首页 > 解决方案 > 有没有办法改变 strptime() 的阈值?

问题描述

Pythonstrptime()函数将所有年份小于 69 的日期(格式为 dd-mm-yy)转换为 20XX 和高于 19XX。

有没有办法调整这个设置,注意在文档中找到。

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)

标签: pythonpython-3.xdatetimestrptime

解决方案


我想出了这个解决方案来将 更改threshold1950-2049作为示例,但是您可以通过更改函数中的阈值变量值来根据需要调整/移动它:

from datetime import datetime, date

dateResult1950 = datetime.strptime('31-07-50', '%d-%m-%y').date()
dateResult2049 = datetime.strptime('31-07-49', '%d-%m-%y').date()

def changeThreshold(year, threshold=1950):
    return (year-threshold)%100 + threshold

print(changeThreshold(dateResult1950.year))
print(changeThreshold(dateResult2049.year))
#1950
#2049

推荐阅读