How to check if a date is valid or not in python

Python program to check if a date is valid :

In this tutorial, we will check if a date is valid or not usng python.

Solution :

1. Get the input from the user
2. Input should be in the form of dd/mm/yy
3. Extract the inputs in different variables
4. use ‘datetime’ module to check if the date is valid or not

Program :

import datetime

inputDate = input("Enter the date in format 'dd/mm/yy' : ")

day,month,year = inputDate.split('/')

isValidDate = True
try :
    datetime.datetime(int(year),int(month),int(day))
except ValueError :
    isValidDate = False

if(isValidDate) :
    print ("Input date is valid ..")
else :
    print ("Input date is not valid..")

The above example is compatible with python3. First, we get the date from user input as ‘dd/mm/yy’ . Using ‘split’ , day,month and year is calculated from that string. And finally, using datetime() method of datetime module, we are checking if the input string is valid date or not.

Sample Example :

Enter the date in format 'dd/mm/yy' : 12/12/2006
Input date is valid ..

Enter the date in format 'dd/mm/yy' : 12/23/2006
Input date is not valid..

Enter the date in format 'dd/mm/yy' : 30/02/2006
Input date is not valid..

Leave a Reply