pythondate-formattingiso8601python-dateutil

python string to date ISO 8601


I am converting many obscure date formats from an old system. The dates are unpacked/processed as strings and converted into ISO 8601 format.

This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function name says it all. Dates from the year 2000 make this messy and clearly this is not the most pythonic way of handling them. How can I make this better using the dateutil.parser?

def YYMMDD0FtoYYYYMMDD(date):
    YY  = date[0:2]
    MM  = date[2:4]
    DD  = date[4:6]
    if int(YY) >= 78:
        YYYY = '19%s' % YY
    elif 0 <= int(YY) <= 77 and MM!='' and MM!='00': 
        YYYY = '20%s' % YY
    else:
        YYYY = '00%s' % YY
    return "%s-%s-%s" % (YYYY, MM, DD)  

Solution

  • You may want to look at the datetime module. Using its date formatting functions, you can do something like this:

    >>> import datetime as dt
    >>> ds = '0104160F'
    >>> parsed = dt.datetime.strptime(ds, "%y%m%d0F")
    >>> parsed
    datetime.datetime(2001, 4, 16, 0, 0)    
    >>> reformatted = dt.datetime.strftime(parsed, "%Y-%m-%d")
    >>> reformatted
    '20010416'
    

    In your function, you can use these as follows:

    def YYMMDD0FtoYYYYMMDD(date):
        return dt.datetime.strftime(dt.datetime.strptime(date, "%y%m%d0F"), "%Y-%m-%d")