Checking if date is valid with two different format

Viewed 136

So I've created the following function, the idea is to check whether the data is either in YYYY-MM-DD or MM/DD/YYYY formats and return a corresponding value. If not return -1.

from datetime import datetime

def dateValidate(date):

    try:
        if date != datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m-%d"):
                raise ValueError
        return 1
        if date == datetime.strptime(date, "%m/%d/%Y").strftime("%m/%d/%Y"):
                raise ValueError
        return 2
    except ValueError:
        return -1

However it doesn't seem to work for the MM/DD/YY format. Any ideas on what's going wrong?

Edit:

import datetime

def validate(date):
    try:
        if date != datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m-%d"):
            raise ValueError
        return 1
    except ValueError:
        return -1
    try:
        if date == datetime.datetime.strptime(date, "%m/%d/%Y").strftime("%m/%d/%Y"):
            raise ValueError
        return 2
    except ValueError:
        return -1

This returns -1 for validate('07/15/1996').

2 Answers

Simply do try for each datetime.strptime and catch each error seperatly.

def dateValidate(date):
    try:
        datetime.strptime(date, "%Y-%m-%d")
        return 1
    except ValueError:
        try:
            datetime.strptime(date, "%m/%d/%Y")
            return 2
        except ValueError:
            return -1

Trial and error is not really a bad way, but here you should wonder what actually happens.

datetime.strptime(string, format) either returns a datetime value, or raise a ValueError. So it is no use to convert back to a string with strftime, unless you intend to test the standard library...

And it is useless to add code after a return (in the same branch of a if) because after the return, the function just return to its caller.

So you must use a try: except to test for a format, return in the try block (if you reach the return, the format was correct), and iterate with a new try: except: in the first except block:

def dateValidate(date):
    try:
        _ = datetime.strptime(date, "%Y-%m-%d")
        return 1
    except ValueError:
        try:
            _ = datetime.strptime(date, "%m/%d/%Y")
            return 2
        except ValueError:
            return -1
Related