gpt4 book ai didi

Python 时间模块无法处理 1900 年之前的年份

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:57 25 4
gpt4 key购买 nike

我想从文本文件转换出生日期。比方说,我有数据

fjsffk 1985-01-30
fkgskgks 1899-02-20

我试过下面的代码,还是报错:

import datetime

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
with open('file.txt', 'r') as f:
for line in f.readlines():
dob = line.rsplit(None, 1)[-1]
dt = datetime.strptime(dob, "%Y-%m-%d")
print "{0:} {1:}, {2:}".format(months[dt.month-1], dt.day, dt.year)

任何解决方案,谢谢!

最佳答案

根据 python tutorial

The exact range of years for which strftime() works also varies across platforms. Regardless of platform, years before 1900 cannot be used.

请耐心等待 - 我已经尝试了以下解决方案并且对我来说效果很好:

from datetime import datetime

mDt = datetime(1900,01,01)
dt = datetime.strptime('20-02-1899', "%d-%m-%Y")
resultString = datetime(dt.year + (mDt - dt).days/365 + 1, dt.month, dt.day).strftime('%B %d, %Y').replace('1900', str(dt.year))

或者像这样:

monthes = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
dt = datetime.strptime('20-02-1890', "%d-%m-%Y")
print "{0:} {1:}, {2:}".format(monthes[dt.month-1], dt.day, dt.year)

关于Python 时间模块无法处理 1900 年之前的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6571562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com