Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format.
Examples:
Input : test_str = ’04-01-1997′, format = “%d-%m-%Y”
Output : True
Explanation : Formats match with date.
Input : test_str = ’04-14-1997′, format = “%d-%m-%Y”
Output : False
Explanation : Month cannot be 14.
Method #1 : Using strptime()
In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity.
# Python3 code to demonstrate working of# Validate String date format# Using strptime()from datetime import datetime
# initializing stringtest_str = '04-01-1997'
# printing original stringprint("The original string is : " + str(test_str))
# initializing format format = "%d-%m-%Y"
# checking if format matches the date res = True
# using try-except to check for truth valuetry:
res = bool(datetime.strptime(test_str, format))
except ValueError:
res = False
# printing resultprint("Does date match format? : " + str(res))
|
Output:
The original string is : 04-01-1997 Does date match format? : True
Method #2 : Using dateutil.parser.parse()
In this, we check for validated format using different inbuilt function, dateutil.parser. This doesn’t need the format to detect for a date.
# Python3 code to demonstrate working of# Validate String date format# Using dateutil.parser.parsefrom dateutil import parser
# initializing stringtest_str = '04-01-1997'
# printing original stringprint("The original string is : " + str(test_str))
# initializing format format = "%d-%m-%Y"
# checking if format matches the date res = True
# using try-except to check for truth valuetry:
res = bool(parser.parse(test_str))
except ValueError:
res = False
# printing resultprint("Does date match format? : " + str(res))
|
Output:
The original string is : 04-01-1997 Does date match format? : True

