lundi 17 décembre 2018

Python datetime pattern matching

I'm trying to identify if a string can be cast as a date, according to a list of different formats. Thus, the whole list has to be looped over. If a match is found, that match should be returned. If all attempts return errors, that error should be returned. I'm not quite sure how to do this, my approach can be seen below.

_DEFAULT_PATTERNS = ["%d.%m.%Y", "%y-%m-%d"]
try:
    if format == 'default':
        for p in _DEFAULT_PATTERNS:
        try:
            value = datetime.strptime(value, p).date()
        except:
            continue
except Exception:
    return ERROR

return value

Aucun commentaire:

Enregistrer un commentaire