Alexey Sh. Alexey Sh. - 1 year ago 94
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' ?


Answer Source

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'):
            return datetime.strptime(text, fmt)
        except ValueError:
    raise ValueError('no valid date format found')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download