如何解析2位数年份的字符串日期? [英] How to parse string dates with 2-digit year?

查看:238
本文介绍了如何解析2位数年份的字符串日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析表示6位数日期的字符串,格式为 yymmdd 其中 yy 的范围为59到05 (1959年至2005年)。根据 时间 模块文档,Python的默认枢轴年是1969年,这对我来说不起作用。

I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module docs, Python's default pivot year is 1969 which won't work for me.

有没有一个简单的方法来覆盖枢纽年,或者你可以提出一些其他解决方案吗?我使用的是Python 2.7。谢谢!

Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!

推荐答案

我会使用 datetime 并解析出来。然后如果超过您的上限日期,我将使用对象上的 datetime.datetime.replace - 将其调整回100年:

I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:

import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
   dd = dd.replace(year=dd.year-100)

这篇关于如何解析2位数年份的字符串日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆