有没有办法改变strptime()的阈值?

问题描述 投票:3回答:2

Python的strptime()函数将年份小于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)

python python-3.x datetime strptime
2个回答
1
投票

几乎可以肯定你的答案:不是没有Python补丁。

从CPython _strptime.py的第375行:

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

您可以在调用strptime之前通过自己的YY到YYYY转换来模拟替代方案。

技术警告回答:Python是一种解释性语言,其中模块以一种易于理解的方式导入,您可以在初始化运行时从技术上操纵_strptime对象,并替换为您自己的函数,也许是一个装饰原始函数。

您需要一个非常好的理由在生产代码中执行此操作。我曾经使用另一个核心库来解决操作系统错误,与团队讨论何时需要删除它。对于你的代码的任何未来维护者来说,这是非常不直观的,9999/10000次,在你自己的代码中调用一些实用程序库会更好。如果你真的需要这样做,很容易解决,所以我将跳过代码示例以避免复制/粘贴。


2
投票

我提出了将threshold更改为1950-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
© www.soinside.com 2019 - 2024. All rights reserved.