Check if the given date is valid or not in Python
Hello friends, in this tutorial I will tell you how to check the validity of a date in Python.
Check validity of a date in Python
To check the validity, I have used the datetime module. Datetime module is an inbuilt library, by which we can perform a variety of activities on date and time. Before beginning, I have imported the dependency to my code. In this tutorial, I’ve used two different objects of datetime function :
- date object
- datetime object
1 . date object
Code :
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.")
Using the map function, I’ve taken a date as input in string format and type casted it as integer values. Using the date object of datetime function, I’ve passed the date, month and year as argument. This function raises a ValueError if the specified values are not in range. This is why I have used the try-except block. You can check out more about it from our tutorial on Handling Exceptions using try and except in Python.
2 . datetime object
You can also use the datetime object instead of date. It works similarly.
Code :
import datetime d, m, y = map(int, input().split()) try: s=datetime.datetime(y,m,d) print("Date is valid.") except ValueError: print("Date is invalid.")
Output :
The output for both the objects will be the same, as they both raise a ValueError if the value is out of range.
31 2 2019 Date is invalid. 24 02 2020 Date is valid. 98 10 3201 Date is invalid.
You can now check the validity of a date in Python.
Leave a Reply