How to parse string dates with 2-digit year?

前端 未结 6 1982
天命终不由人
天命终不由人 2020-12-17 07:42

I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module

相关标签:
6条回答
  • 2020-12-17 08:09

    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
    
    0 讨论(0)
  • 2020-12-17 08:13

    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.

    0 讨论(0)
  • 2020-12-17 08:22
    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' )
    
    0 讨论(0)
  • 2020-12-17 08:27

    If you are dealing with very recent dates as well as very old dates and want to use the current date as a pivot (not just the current year), try this code:

    import datetime
    def parse_date(date_str):
        parsed = datetime.datetime.strptime(date_str,'%y%m%d')
        current_date = datetime.datetime.now()
        if parsed > current_date:
            parsed = parsed.replace(year=parsed.year - 100)
        return parsed
    
    0 讨论(0)
  • 2020-12-17 08:31

    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)
    
    0 讨论(0)
  • 2020-12-17 08:33

    You can also perform the following:

    today=datetime.datetime.today().strftime("%m/%d/%Y")
    today=today[:-4]+today[-2:]
    
    0 讨论(0)
提交回复
热议问题