check the input format of a date python

Solutions on MaxInterview for check the input format of a date python by the best coders in the world

showing results for - "check the input format of a date python"
Sofia
04 Sep 2019
1>>> import datetime
2>>> def validate(my_str_date):
3    try:
4        datetime.datetime.strptime(my_str_date, '%Y-%m-%d')
5    except ValueError:
6        raise ValueError("Incorrect data format, should be YYYY-MM-DD")
7        
8
9>>> validate('2003-12-23')
10>>> validate('2003/12/23')
11
12Traceback (most recent call last):
13  File "<stdin>", line 1, in <module>
14  File "<stdin>", line 5, in validate
15ValueError: "Incorrect data format, should be YYYY-MM-DD"
16