0

I'm trying to identify which is the date format considering only two options %Y-%m and %Y-%m-%d.

If it is Y-m or Y-m-d it is getting ok. The problem is that I want to insert an error sentence in the case the format is neither one of those, like this:

date='2014-01asd'

def date_format(date):  
    try:  
        datetime.datetime.strptime(date, '%Y-%m')  
        return 1  
    except ValueError:  
        datetime.datetime.strptime(date, '%Y-%m-%d')  
        return 2  
    except:  
        return 'Wrong date format you dweezle! Must be YYYY-MM or YYYY-MM-DD'

However apparently it is not possible to use two "excepts" in sequence. Con someone help?

1 Answer 1

2

You need to nest your try...except statements here:

def date_format(date):  
    try:  
        datetime.datetime.strptime(date, '%Y-%m')  
        return 1  
    except ValueError:  
        try:
            datetime.datetime.strptime(date, '%Y-%m-%d')  
            return 2  
        except ValueError:  
            return 'Wrong date format you dweezle! Must be YYYY-MM or YYYY-MM-DD'

although you could just put them in series, since the first will return out of the question if successful; have the first exception handler pass:

def date_format(date):  
    try:  
        datetime.datetime.strptime(date, '%Y-%m')  
        return 1  
    except ValueError:
        pass

    try:
        datetime.datetime.strptime(date, '%Y-%m-%d')  
        return 2  
    except ValueError:  
        return 'Wrong date format you dweezle! Must be YYYY-MM or YYYY-MM-DD'
Sign up to request clarification or add additional context in comments.

1 Comment

if it might be more than a couple of date formats then a loop could eliminate the code duplication (ignore text, look at the code examples).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.