How to check if the given date is valid or not in Python
In this tutorial, We will see how to check if the given date is valid or not in Python. A simple solution comes to our mind is that just check calendar if it is in then valid else invalid. For example date 31-02-2000 is invalid. In order to solve this problem, we have to use datetime module and try-except statement in our program. Before going to understand Python program we have to learn datetime module and try-except statements.
What is datetime module in Python?
Python has an inbuilt datetime module which provides us to solve various problems related to date and time.
The basic syntax of try-except statements:
try: #code except: #code
- If the code provided in try block has no exception then only try executed.
- If any exception occurs in block of try then try block skipped and except block will be executed.
We will follow these steps to solve the above problem in python:
- First of all, We will import the datetime module in the program.
- Take the input as a date from the user and we are going to suppose the date provided from the user is 31-02-2019.
- We will use the try-except statements as when the date will going to invalid, it shows ValueError during the execution of code.
Python program to check the given date is valid or not
So, let’s start writing program in python following the above steps.
import datetime d,m,y=map(int,input().split()) try: s=datetime.date(y,m,d) print("Date is valid.") except ValueError: print("Date is invalid.")
31 2 2019
29 2 2019
28 2 2019
Date is invalid.
Date is invalid.
Date is valid.
So Guy’s, I hope you find it really useful.
- How to find the difference or gap of days between two dates in python
- Find the day of week with a given date in Python