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 using Python. A date is called valid if it actually exists in the calendar.

Our program will ask the user to enter the date at the beginning of the program. It will then check the validity of the date and print out the result on the console.

For example, if the date is ‘01/02/2012’, it will print ‘Input date is valid’ and if the date is ‘31/02/2012’, it will print ‘Input date is not valid.’.

To check the validity of the date, we will use one Python module called ’datetime’. This module doesn’t provide any dedicated method to check if a date is valid or not but we will use this module with a simple trick to find out if a date is valid or not.

Before going into details, let me quickly introduce you to the datetime module :

Python datetime module :

Python datetime module is one of the most useful modules to work with simple and complex date-time values. We can import this module to a Python program by using the import datetime statement at the beginning of a program.

This module provides a lot of different methods to work with date-time. For example, we can use this module to print the current time, add days to the current time, add hours to the current time, add minutes to the current time etc.

The ’datetime’ module can work with ’naive’ and ’aware’ kinds of date-time objects.

  • aware’ objects can hold additional information with the date time value like daylight saving information etc. These objects are useful if we are dealing with data from different timezones.

  • naive’ objects don’t contain any such information. These objects are easy to understand and we can use them if information like timezone, daylight saving etc. are not required.

The smallest year supported by the ’datetime’ module is stored in the MINYEAR variable and the maximum supported year is stored in the MAXYEAR variable. The value of MINYEAR is 1 and MAXYEAR is 9999.

As I have explained above, it doesn’t provide any method to check the validity of a date. We will use its constructor to create one ’datetime’ object using the user-provided string. If the constructor fails, it will throw one error and we can say that the input string is not representing a valid date-time.

The Algorithm to use :

  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. e.g. if the user input is 02/04/99, we will extract the numbers 02, 04, and 99 and store them in three different variables.
  4. Use the constructor of ‘datetime’ module to check if the date is valid or not.
  5. Print out the result.

Python 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..")

python check if date is valid

  1. The above example is compatible with python3. First of all, we are getting the date from the user as ‘dd/mm/yy’.
  2. By using the split method, we are extracting the day, month and year values from the string.
  3. The isValidDate flag is used to determine if the user-provided date is valid or not. If its value is True, it is a valid date, else it is not.
  4. datetime.datetime() is the constructor we are using to create one ‘datetime’ variable by using the user provided values. If it fails, it will throw one ’ValueError’. We are setting the value of ’isValidDate’ flag to ’False’ here.
  5. Finally, print out the result to the user based on the value of ’isValidDate’ flag.

Sample Example :

python check if date is valid

Method 2: By using datetime.strptime() method:

If we use the datetime.datetime constructor, we have to split the date-time string to get the year, month and day values. Instead of splitting the string, we can also use the datetime.strptime() method. We can define the format string and it will use that format string to parse the given date string.

It raises ValueError if the string can’t be parsed as defined by the format. Similar to the above example, we can use a try-catch block to check if the given string is a valid date-time string or not.

Following are the list of all the format code:

Directive Meaning
%a Weekday as locale’s abbreviated name e.g. Sat, Sun
%A Weekday as locale’s full name e.g. Saturday, Sunday
%d Zero padded day of month e.g. 01, 02 etc.
%w Weekday in number from 0 to 6, 0 is for Sunday
%b Local’s abbreviated month name e.g. Jan, Feb
%B Month as locale’s full name e.g. January, February
%m Zero padded decimal month value e.g. 01, 02
%y Zero padded decimal year value e.g. 00, 01
%Y Year with century as decimal e.g. 0001, 2013,…9999
%H 24 hour clock as a zero-padded number e.g. 00, 01,…23
%I 12 hour clock as a zero-padded number e.g. 00, 01,…12
%p Locale’s equivalent AM/PM value
%M Minute as zero padded number e.g. 00, 01,…59
%S Second as zero padded number e.g. 00, 01,…59
%f Microsecond as zero padded number upto 6 digits e.g. 000000
%Z Time zone name, it will be empty if the object is naive e.g. UTC
%z UTC offset in the form of ±HHMM[SS[.ffffff]], empty if the object is naive
%U Week number of the year as zero-padded number
%j Day of the year as zero-padded number e.g. 001, 002,…, 366
%W Week number of the year as zero-padded number
%x Locale’s appropriate date representation
%X Locale’s appropriate time representation
%c Locale’s appropriate date and time representation
%% % character

Source: python doc

Let’s use this method to check if a date is valid or not:

from datetime import datetime

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

date_format = "%d/%m/%y"

isValidDate = True
try:
    datetime.strptime(inputDate, date_format)
except ValueError:
    isValidDate = False

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

This approach is better than the previous one as we need to pass the format instead of splitting the string to find the values.

Output:

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

Method 3: By using python-dateutil:

With this method, we will use the python-dateutil module to check if a date-time string is valid or not. This module provides extension functions to the datetime module. You can use the below command to add it to your project:

pip install python-dateutil

This module provides a parser function that can parse most of the known date-time formats. Unlike the above example, we don’t need to pass the format string to this function.

It can throw a ParseError for an invalid string. We can use a try-catch block to check if the date string is valid or not.

from dateutil import parser

inputDate = input("Enter the date in any valid format: ")

isValidDate = True
try:
    print(parser.parse(inputDate))
except ValueError:
    isValidDate = False

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

Sample output:

Enter the date in any valid format: 31-03-22
2022-03-31 00:00:00
Input date is valid ..

Enter the date in any valid format: 03-31-22
2022-03-31 00:00:00
Input date is valid ..

Conclusion:

We learned three different ways to check if a date-time string is valid or not. The datetime.strptime method is better if you want to test the string with a predefined format string. If we don’t know the format and we just want to know if a string represents a valid date-time or not, we can use the python-dateutil module.

Similar tutorials :