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

后端 未结 2 977
难免孤独
难免孤独 2020-12-06 11:15

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 do

2条回答
  •  生来不讨喜
    2020-12-06 11:47

    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.

提交回复
热议问题