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