Alexey Sh. Alexey Sh. - 7 days ago 8
Python Question

How to format date string via multiple formats in python

I have three date formats: 'YYYY-MM-DD', 'DD.MM.YYYY', 'DD/MM/YYYY'

Is it possible to validate and parse strings as '2014-05-18' or '18.5.2014' or '18/05/2019' ?

Thanks

Answer

Try each format and see if it works:

from datetime import datetime

def try_parsing_date(text):
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%y'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')
Comments