This tutorial will discuss about a unique way to check if date is valid in Python.
Suppose we have a date in this string format like this,
dateStr1 = '2023-04-24'
We want to check if it is a valid date or not. By valid we mean that this date actually exist. Suppose if someone give us a date like 2023-02-30 i.e. 30th february, it does not exist or suppose 45th March, that too does not exist. So we need to check if a given date is valid or not.
We have created a method for this,
from datetime import datetime def is_valid(dateStr): # Checks if a given date string is a valid date. # Returns True, if date string is valid, False otherwise. result = True try: datetime.strptime(dateStr, '%Y-%m-%d') except ValueError: result = False return result
It accepts a date in the string format and check sif the given date string is valid or not. It returns True, if the give date string is valid, otherwise it returns false.
Frequently Asked:
Inside the method, we will convert the date in string format to datetime object using the strptime() method. In which, we will pass the date string as first argument and the format in which date is stored in the string as a second argument. If it is a valid date, then strptime() will return a datetime object, but if it is not a valid date did then strptime() method will raise the value error.
We can catch this exception to check if the given date is valid or not. In the below example, we can use the this method to check if we given date string is valid or not.
Let’s see the complete example,
from datetime import datetime def is_valid(dateStr): # Checks if a given date string is a valid date. # Returns True, if date string is valid, False otherwise. result = True try: datetime.strptime(dateStr, '%Y-%m-%d') except ValueError: result = False return result ## Example 1 dateStr1 = '2023-04-24' # Check if dateStr1 is a Valid date if is_valid(dateStr1): print('Yes, Date is Valid') else: print('No, Date is not Valid') ## Example 2 dateStr2 = '2023-02-31' # Check if dateStr2 is a Valid date if is_valid(dateStr2): print('Yes, Date is Valid') else: print('No, Date is not Valid')
Output
Best Resources to Learn Python:
Yes, Date is Valid No, Date is not Valid
Summary
We learned about a way to check if a date is valid or not in Python.
Leave a Reply
You must be logged in to post a comment.