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..

3 Replies to “How to check if a date is valid or not in python”

  1. 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.

  2. Shalom Nyende says: Reply

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

  3. Aivar Paalberg says: Reply

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

    datetime.datetime(int(year),int(month),int(day))

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

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

    More information in Python documentation: https://docs.python.org/3.6/library/datetime.html#datetime.datetime.strptime

Leave a Reply