Python program to check if a date is valid :

In this tutorial, we will check if a date is valid or not using 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 :
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 are 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..

You might also like :

Categories: python


meno · March 17, 2018 at 3:25 am

just a quick comment, in passing… I have been accustomed to setting a ‘verify’ boolean variable (e.g., isValidDate) to False by default, and then only set it to True once I have confirmed the assertion has been made.
This is just my opinion.
Thank you for sharing your work.

Shalom Nyende · April 18, 2018 at 10:06 am

Perhaps I am a little late for the party. I use python’s dateutil module:
>>>from dateutil.parser import parse
Returns a valid datetime object.
You can feed it dates separated by / or –

Aivar Paalberg · May 22, 2018 at 10:20 am

There is possibility to skip splitting the inputDate and instead of doing validity check with:


one can parse time directly from string using strptime() method:

datetime.datetime.strptime(inputDate, ‘%d/%m/%y’)

More information in Python documentation:

Leave a Reply

Your email address will not be published. Required fields are marked *