How to format date string via multiple formats in python

Alexey Sh. picture Alexey Sh. · May 10, 2014 · Viewed 30.7k times · Source

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

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

Answer

Jon Clements picture Jon Clements · May 10, 2014

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')