Search code examples
pythondatetimedatetime-formatpython-datetime

Date validator / formatter returns None?


I need a function that takes a date string as input, and either validates that the input is formatted %m/%d%Y (MM/DD/YYYY) or reformats the given date to that format. However when I run the following, I print: "date is: None". Can anybody lend some guidance how to resolve this issue? Any help is greatly appreciated!

import datetime

test_date = "08/19/2020"

def date_fixer(date_string):
    '''takes a date as input and reformats if needed.'''
    format = "%m/%d/%Y"
    date_string = str(date_string)
    try:
        datetime.datetime.strptime(date_string, format)
        print("This is the correct date string format.")
    except ValueError:
        print("This is the incorrect date string format. It should be %m/%d/%Y")
        #convert
        date_string = parse(str(date_string)).strftime('%m/%d/%Y')
        return(date_string)

date = date_fixer(test_date)
print("date is: " + str(date))

Solution

  • The return was inside the except block, thats the reason why it was returning None when the date format was valid.

    Can you try the following:

    import datetime
    
    test_date = "08/19/2020"
    
    def date_fixer(date_string):
        '''takes a date as input and reformats if needed.'''
        format = "%m/%d/%Y"
        date_string = str(date_string)
        try:
            datetime.datetime.strptime(date_string, format)
            print("This is the correct date string format.")
        except ValueError:
            print("This is the incorrect date string format. It should be %m/%d/%Y")
            #convert
            date_string = parse(str(date_string)).strftime('%m/%d/%Y')
        return(date_string)
    
    date = date_fixer(test_date)
    print("date is: " + str(date))