pythonpandasdatedatetimepattern-recognition

How to define a function that recognizes my date format in python


I want to create a function or a loop with the conditional: if this string follows this format is a date, so return True, otherwise return False.

I already tried it with this code, but when I run is_date(string) it returns False, and it should return True.

string = '20090903'
def is_date(string):
    if string.format == "%YYYY%mm%dd":
        return True
    else:
        return False
is_date(string)

Solution

  • Try checking if the length is eight and the string only contains digits:

    string = '20090903'
    def is_date(string):
        return len(string) == 8 and string.isdigit()
    print(is_date(string))
    

    A more precise solution:

    string = '20090903'
    from dateutil.parser import parse 
    def is_date(string):
        try:
            parse(string)
            return True
        except:
            return False
    print(is_date(string))
    

    This solution will give False on 00000000, but not the first solution:

    Both Output:

    True