1

I'm currently coding an account signup on python and I need the user to enter their date of birth in the format DD/MM/YYYY.

How would I be able to check in the code if the input is valid or not?

dob=input("Enter your date of birth in the format DD/MM/YYYY")
Wool
  • 138
  • 1
  • 10
D.Elsom
  • 13
  • 1
  • 4

3 Answers3

2
import datetime

try:
    date_of_birth = datetime.datetime.strptime(dob, "%d/%m/%Y")
except:
    print("Incorrect date!")
Błotosmętek
  • 12,717
  • 19
  • 29
1

Use following code

from datetime import datetime
i = str(raw_input('date'))
try:
    dt_start = datetime.strptime(i, '%d/%m/%Y')
except ValueError:
    print "Incorrect format"
Jay Parikh
  • 2,419
  • 17
  • 13
0

Try using the datetime library

from datetime import datetime  
def validate(date_text):
        try:
            datetime.datetime.strptime(date_text, '%d/%m/%Y')
        except ValueError:
            raise ValueError("Incorrect data format, should be YYYY-MM-DD")
Akshay Apte
  • 1,539
  • 9
  • 24