Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strptime parsing year without century: assume prior to this year?

I am parsing some datetime strings in Python 2.7, using datetime.strptime. I want to assume that a date is prior to now.

But strptime's %y operator does not do this by default:

d = '10/12/68'
n = datetime.strptime(d, '%d/%m/%y')
print n
2068-12-10 00:00:00

Is there any way I can get Python to assume that 68 is 1968, as it would be in common usage?

Or should I just parse the string and insert 19 or 20, as appropriate, manually?

like image 816
Richard Avatar asked Oct 29 '15 06:10

Richard


1 Answers

If your input is in the local timezone:

from datetime import date

then = datetime.strptime('10/12/68', '%d/%m/%y').date()
if date.today() <= then: # *then* must be in the past
    then = then.replace(year=then.year - 100)

It should work ok until 2100 (excluding). See here for more details on arithmetic with calendar years.

like image 142
jfs Avatar answered Oct 06 '22 00:10

jfs