aabujamra
aabujamra

Reputation: 4636

Identifying date format in a string - Python

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?

Upvotes: 0

Views: 132

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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'

Upvotes: 2

Related Questions