有没有办法改变 strptime() 的阈值?
Is there a way to change the threshold for strptime()?
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)
我想出了这个解决方案,以将 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
几乎可以肯定你的答案:不是没有 Python 补丁。
来自 C 中的第 375 行Python _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
您可以在调用 strptime 之前通过自己将 YY 转换为 YYYY 来模拟替代方案。
技术警告答案:Python 作为一种解释型语言,模块以易于理解的方式导入,您可以在技术上在初始化运行时操作 _strptime
对象并替换为您自己的函数,或许一个装饰原来的。
在生产代码中执行此操作需要非常充分的理由。我用另一个核心库做了一次来解决 OS 错误,与团队讨论何时需要删除它。对于您的代码的任何未来维护者来说,这都是非常不直观的,9999/10000 次最好只在您自己的代码中调用一些实用程序库。如果你真的需要这样做,很容易解决,所以我将跳过代码示例以避免 copy/pasters.
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)
我想出了这个解决方案,以将 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
几乎可以肯定你的答案:不是没有 Python 补丁。
来自 C 中的第 375 行Python _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
您可以在调用 strptime 之前通过自己将 YY 转换为 YYYY 来模拟替代方案。
技术警告答案:Python 作为一种解释型语言,模块以易于理解的方式导入,您可以在技术上在初始化运行时操作 _strptime
对象并替换为您自己的函数,或许一个装饰原来的。
在生产代码中执行此操作需要非常充分的理由。我用另一个核心库做了一次来解决 OS 错误,与团队讨论何时需要删除它。对于您的代码的任何未来维护者来说,这都是非常不直观的,9999/10000 次最好只在您自己的代码中调用一些实用程序库。如果你真的需要这样做,很容易解决,所以我将跳过代码示例以避免 copy/pasters.