check whether the given date value is valid or not in python with django

2.9k views Asked by At

I need to check whether the given input value of date is valid or not in python. I normally used datetime.strptime is to check for date. Am getting Value Error doesn't match format when i given the input value date '06-06-'. It's wrong only but i want to display the output like invalid.

  if (datetime.strptime(s,'%m-%d-%y')):
       print "valid"
  else:
       print "Invalid"

1 . s = '06-06-15' when i given the input value like above, it display the correct output value "Valid"

  1. s = '06-06-' when i given the input value like above, am getting error like time data '06-13' does not match format '%m-%d-%y'. But i want to display the output "Invalid"

Please anyone suggest me to do that. Thanks in advance.

1

There are 1 answers

0
deathangel908 On BEST ANSWER

This is just how it works.

ValueError is raised if the date_string and format can’t be parsed by time.strptime()

Just turn it to

datetime.strptime(s,'%m-%d-%y'):
       print "valid"
except ValueError:
       print "Invalid"