Python 如何用两位数的年份解析字符串日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16600548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse string dates with 2-digit year?
提问by blah238
I need to parse strings representing 6-digit dates in the format yymmddwhere yyranges from 59 to 05 (1959 to 2005). According to the timemodule docs, Python's default pivot year is 1969 which won't work for me.
我要代表格式6位数的日期解析字符串yymmdd,其中yy范围从59到05年(1959至2005年)。根据time模块文档,Python 的默认枢轴年份是 1969,这对我不起作用。
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
是否有一种简单的方法可以覆盖枢轴年,或者您能否提出其他解决方案?我正在使用 Python 2.7。谢谢!
采纳答案by mgilson
I'd use datetimeand parse it out normally. Then I'd use datetime.datetime.replaceon the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
我会datetime正常使用和解析它。然后datetime.datetime.replace,如果它超过了您的上限日期,我会在该对象上使用- 将其调整回 100 年:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
回答by msw
Prepend the century to your date using your own pivot:
使用您自己的枢轴将世纪添加到您的日期之前:
year = int(date[0:2])
if 59 <= year <= 99:
date = '19' + date
else
date = '20' + date
and then use strptimewith the %Ydirective instead of %y.
然后strptime与%Y指令一起使用而不是%y.
回答by Pic
import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
dt = dt.replace( year=dt.year-100 )
^2053 ^1953
print dt.strftime( '%Y-%m-%d' )
回答by anajem
You can also perform the following:
您还可以执行以下操作:
today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]
回答by wittrup
Recently had a similar case, ended up with this basic calculation and logic:
最近有一个类似的案例,最终得到了这个基本的计算和逻辑:
pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100
def year_2to4_digit(year):
return century + year if century + year > pivotyear else (century + 100) + year

