2

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').

martineau
  • 119,623
  • 25
  • 170
  • 301
fynmnx
  • 571
  • 6
  • 29

2 Answers2

4

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
xIsra
  • 867
  • 10
  • 21
  • I just tried this and it does not return the correct value for '07/15/1996' which should be 2. Please check the edit i made to the original post. It wouldn't make sense though because after the first try, it will obviously return -1 as the try statement didn't go through. – fynmnx Jun 30 '19 at 20:46
  • @Safder Look at the updated answer. – xIsra Jun 30 '19 at 21:04
  • Perfect! I get it now, I couldn't get the value error in the right spots. – fynmnx Jun 30 '19 at 21:15
0

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
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252