Search code examples
pythonvalidationdatedatetimepython-datetime

Date validation and conversion to European format Python


I am trying to write code (Python) that would check date format of an input and then convert it to DD-MM-YYYY (if input format differs from DD-MM-YYYY). I have checked similar questions on StackOverflow but they are all concerned with either validating or converting format and I have no idea how to do both at the same time. I can't block input in other formats as it comes from external source.

So far I wrote this:

import datetime
YearOfBirthString = '05-30-1960'
if YearOfBirthString != '':
    if datetime.datetime.strptime(YearOfBirthString, '%d-%m-%Y'):
        print(YearOfBirthString)
    elif datetime.datetime.strptime(YearOfBirthString, '%Y-%m-%d'):
        correctDate = datetime.datetime.strptime(YearOfBirthString, '%Y-%m-%d').strftime('%d-%m-%Y')
        print(correctDate)
    elif datetime.datetime.strptime(YearOfBirthString, '%m-%d-%Y'):
        correctDate = datetime.datetime.strptime(YearOfBirthString, '%m-%d-%Y').strftime('%d-%m-%Y')
        print(correctDate)
    elif datetime.datetime.strptime(YearOfBirthString, '%Y-%d-%m'):
        correctDate = datetime.datetime.strptime(YearOfBirthString, '%Y-%d-%m').strftime('%d-%m-%Y')
        print(correctDate)
    else:
        print('Nuffin')
else:
    print('Nuffin')

It works only when the first "If" condition is meet- crashes in any other cases instead of checking all elif conditions. Error message is as follow:

"ValueError: time data '05-30-1960' does not match format '%Y-%m-%d'"

Does anyone know how to deal with it?


Solution

  • You can structure your logic in a function to attempt, sequentially, several datetime formats in a for loop. Then return when a specific format succeeds.

    This solution involves only datetime from the standard library and try / except to capture unsuccessful attempts.

    from datetime import datetime
    
    YearOfBirthString = '05-30-1960'
    
    def converter(s, format_list, format_output):
        for date_format in format_list:
            try:
                return datetime.strptime(s, date_format).strftime(format_output)
            except ValueError:
                continue      
        return 'Nuffin'
    
    res = converter(YearOfBirthString,
                    format_list=['%d-%m-%Y', '%Y-%m-%d', '%m-%d-%Y', '%Y-%d-%m'],
                    format_output='%d-%m-%Y')
    
    # '30-05-1960'