Python strptime parsing year without century: suppose before this year?

I am parsing some datetime strings in Python 2.7 using datetime.strptime . I want to assume that the date is before.

But the strptime %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 to get Python to suggest that 68 is 1968 , as it would be in normal use?

Or do you just need to parse the string and insert 19 or 20 , if necessary, manually?

+5
source share
2 answers

Easy to fix after the fact:

 from datetime import datetime, timedelta dt = datetime.strptime(...) if dt > datetime.now(): dt -= timedelta(years=100) 
+3
source

If your entry is in the local time zone:

 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 fine until 2100 (excluding). See here for more information on calendar year arithmetic .

+1
source

Source: https://habr.com/ru/post/1234761/


All Articles