PYTHON PROGRAM TO CHECK THE GIVEN DATE IS VALID OR NOT

In this topic, we will discuss how to easily and interestingly to check the given date is valid or not using Python programming language.  Let’s see the modules we will use to check the given date is valid or not.

To Check  The Given Date Is Valid Or Not

 

Table Of Contents:

  • Introduction
  • Program to check the given date is valid or not
  • Output
  • Conclusion

Introduction:

To check the given date format is valid or not and utilize appropriate methods and modules available in Python programming.

The modules are,

  1. Using strptime()
  2. Using dateutil.parser.parse()

Using strptime():

In Python, ‘strptime()’ is a method of ‘datetime’  module.  It stands for “string parse time”.  It is used in two methods:

  • A string representing the date and time.
  • A format string that specifies the format of the input string.

It is used as when the datetime does not match the format or date, raises the ValueError.

from datetime import datetime
str_test = input("Enter the string date to test:")
print("The original string is : " + str(str_test))
format = "%d-%m-%Y"
result = True
try:
    result = bool(datetime.strptime(str_test, format))
except ValueError:
    result = False
print("Is the given date is match the format : " + str(result))

from datetime import datetime:   We want to leverage Python’s built-in datetime module to check whether a given date is valid or not.  It use along with the exception handling.

So, that why we use exception handling up there.

Output:

Enter the string date to test:10-08-2010
The original string is : 10-08-2010
Is the given date is match the format : True

Conclusion:

In the conclusion,  Python programming offers flexible modules and methods to check the given date is valid or not.

Thank you for visiting our site!!!!!…….

Leave a Comment

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

Scroll to Top