简体   繁体   中英

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 Ym or Ymd 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?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM