2 digit years using strptime() is not able to parse birthdays very well

房东的猫 提交于 2019-12-04 03:17:05

问题


Consider the following birthdays (as dob):

  • 1-Jun-68
  • 1-Jun-69

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)

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:

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?


回答1:


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)



回答2:


This function shifts the year to 1950:

def millenium(year, shift=1950):
    return (year-shift)%100 + shift



回答3:


If you're expecting a birthday, you could always just manually massage the data - any date in the future is automatically set back a century, or some such.



来源:https://stackoverflow.com/questions/3283209/2-digit-years-using-strptime-is-not-able-to-parse-birthdays-very-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!