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

后端 未结 2 967
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2020-12-06 12:06

    It's easy to fix after the fact:

    from datetime import datetime, timedelta
    dt = datetime.strptime(...)
    if dt > datetime.now():
        dt -= timedelta(years=100)
    
    0 讨论(0)
提交回复
热议问题