How to parse string dates with 2-digit year?

房东的猫 提交于 2019-11-29 09:04:18

I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:

import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
   dd = dd.replace(year=dd.year-100)

Prepend the century to your date using your own pivot:

  year = int(date[0:2])
  if 59 <= year <= 99:
      date = '19' + date
  else
      date = '20' + date

and then use strptime with the %Y directive instead of %y.

import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
    dt = dt.replace( year=dt.year-100 )
                     ^2053   ^1953
print dt.strftime( '%Y-%m-%d' )
anajem

You can also perform the following:

today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]

Recently had a similar case, ended up with this basic calculation and logic:

pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100

def year_2to4_digit(year):
    return century + year if century + year > pivotyear else (century + 100) + year
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!