["python","date"]
How do I validate a date string format in python?

I have a python method which accepts a date input as a string. How do I add a validation to make sure the date string being passed to the method is in the ffg. format: 'YYYY-MM-DD' if it's not, method should raise some sort of error
>>> import datetime >>> def validate(date_text): try: datetime.date.fromisoformat(date_text) except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") >>> validate('2003-12-23') >>> validate('2003-12-32') Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> validate('2003-12-32') File "<pyshell#18>", line 5, in validate raise ValueError("Incorrect data format, should be YYYY-MM-DD") ValueError: Incorrect data format, should be YYYY-MM-DD Note that datetime.date.fromisoformat() obviously works only when date is in ISO format. If you need to check date in some other format, use datetime.datetime.strptime().