使用strptime()的2位数字年份不能很好地解析生日 [英] 2 digit years using strptime() is not able to parse birthdays very well

查看:160
本文介绍了使用strptime()的2位数字年份不能很好地解析生日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下生日(如dob):

  • 68年6月1日
  • 69年6月1日

用Python的datetime.strptime(dob, '%d-%b-%y')解析时将产生:

When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield:

  • datetime.datetime(2068, 6, 1, 0, 0)
  • datetime.datetime(1969, 6, 1, 0, 0)
  • datetime.datetime(2068, 6, 1, 0, 0)
  • datetime.datetime(1969, 6, 1, 0, 0)

当然,他们应该在同一十年出生,但是现在甚至不在同一世纪!

Well of course they’re supposed to be born in the same decade but now it’s not even in the same century!

根据文档,这是完全有效的行为:

According to the docs this is perfectly valid behaviour:

当接受两位数的年份时,将根据 POSIX或X/Open标准:值69-99映射到1969-1999, 并将0-68的值映射到2000-2068.

When 2-digit years are accepted, they are converted according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and values 0–68 are mapped to 2000–2068.

我了解为什么要像这样设置功能,但是有什么方法可以解决此问题?也许可以定义自己的两位数年份范围?

I understand why the function is set up like this but is there a way to work around this? Perhaps with defining your own ranges for 2-digit years?

推荐答案

如果您始终将其用于生日,则如果减去现在年份,则减去100:

If you're always using it for birthdays, just subtract 100 if the year is after now:

if d > datetime.now():
    d = datetime(d.year - 100, d.month, d.day)

这篇关于使用strptime()的2位数字年份不能很好地解析生日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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