Fix Python – How do I validate a date string format in python?

Question

Asked By – codemickeycode

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

Now we will see solution for issue: How do I validate a date string format in python?


Answer

>>> import datetime
>>> def validate(date_text):
        try:
            datetime.datetime.strptime(date_text, '%Y-%m-%d')
        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

This question is answered By – jamylak

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0