How to do date validation in Python?


In this article, we will show you how to do date validation in Python. Now we see 2 methods to accomplish this task−

  • Using datetime.strptime() function

  • Using dateutil.parser.parse() function

Method 1: Using datetime.strptime() function

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the datetime (To work with dates and times) module.

  • Enter the date as a string and create a variable to store it.

  • Enter the date format as a string and create another variable to store it.

  • Use the try−except blocks for handling the exceptions (In Python, the Try and Except statements are used to handle these errors. The try block is used to check some code for errors, i.e. the code inside the try block will execute if the program contains no errors. The code within the except block, on the other hand, will be executed whenever the program encounters an error in the preceding try block)

  • Within the try block, pass the given date string and date format as arguments to the strptime() function (formats a timestamp in string format into a date−time object) of the datetime class of the datetime module and save the results in a variable. (Read more on Python Date & Time)

  • Print the above result within the try block. Here it prints the formatted date if there is no error.

  • If the above date validation fails then it will execute the except block. Inside the except block, print the appropriate text if ValueError occurs.

Example

The following program returns whether the given date is valid or not using the strptime() function −

# importing datetime module import datetime # input date date_string = '2017-12-31' # giving the date format date_format = '%Y-%m-%d' # using try-except blocks for handling the exceptions try: # formatting the date using strptime() function dateObject = datetime.datetime.strptime(date_string, date_format) print(dateObject) # If the date validation goes wrong except ValueError: # printing the appropriate text if ValueError occurs print("Incorrect data format, should be YYYY-MM-DD")

Output

On executing, the above program will generate the following output −

2017-12-31 00:00:00

You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string.

Directive Meaning
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale's equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale's appropriate date representation.
%X Locale's appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal "%" character

Method 2: Using dateutil.parser.parse() function

In this method, we use a separate inbuilt function, dateutil.parser, to check for validated format. This does not require the format to validate a date.

Algorithm (Steps)

  • Use the import keyword, to import the parser from dateutil module.

The parser module can parse datetime strings in a number of different formats. To parse dates and times in Python, there is no better package than dateutil. The tz module includes everything needed to look for timezones. When these modules are used together, it is relatively simple to convert strings into timezone−aware datetime objects.
  • Enter the date as a string and create a variable to store it.

  • Print the given input date.

  • Use the try−except blocks for handling the exceptions. Inside the try block, parse the given date string using the parse() function. Here it prints true if the given date is correct.

  • If the date is not correct/invalid then the except block code will be executed. Here If there is a parsing error for the given date then it will throw ValueError so the except block handles the ValueError and we print some text to say the given date is not validated.

Example

The following program returns whether the given date is valid or not using the parse() function −

# importing parser from dateutil module from dateutil import parser # input date date_string = '23-41-2021' # printing the input date print("Input Date:", date_string) # using try-except blocks for handling the exceptions try: # parsing the date string using parse() function # It returns true if the date is correctly formatted else it will go to except block print(bool(parser.parse(date_string))) # If the date validation goes wrong except ValueError: # printing the appropriate text if ValueError occurs print("Incorrect data format")

Output

On executing, the above program will generate the following output −

Input Date: 23-41-2021
Incorrect data format

Conclusion

We learned how to validate a given date using two different methods in this article. We also learned about the other directives that strptime() function supports.

Updated on: 27-Aug-2023

29K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements