Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 898
casr Avatar asked Jul 19 '10 17:07

casr


People also ask

Which two parameters does the DateTime Strptime () function requires?

The strptime() class method takes two arguments: string (that be converted to datetime) format code.

What is Strptime ()?

The strptime() function in Python is used to format and return a string representation of date and time.

What does DateTime DateTime Strptime do?

Python DateTime – strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.


2 Answers

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)
like image 128
Matthew Flaschen Avatar answered Sep 25 '22 23:09

Matthew Flaschen


This function shifts the year to 1950:

def millenium(year, shift=1950):
    return (year-shift)%100 + shift
like image 29
SiggyF Avatar answered Sep 26 '22 23:09

SiggyF