python - 有没有办法改变 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
推荐阅读
- c++ - 使用 std::any_of、std::all_of、std::none_of 等与 std::map
- javascript - 如何只运行一次事件监听器?
- machine-learning - 增加 StyleGAN 中的训练迭代次数
- css - Edge浏览器中的图标渲染很慢
- ansible - 全局变量之上的 Ansible 单任务变量
- javascript - 嵌套数组中的“未捕获 RangeError:超出最大调用堆栈大小”
- spring-boot - 使用 MyBatis Annotation Spring Boot 检索生成的 ID
- php - php使用不同的表单从另一个表单获取数据
- elasticsearch - Elasticsearch 搜索请求仅限于某些服务器 IP
- ios - 检测应用程序何时在后台状态iOS中被用户杀死