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
from datetime import datetime
test_str = '04-01-1997'
print("The original string is : " + str(test_str))
format = "%d-%m-%Y"
res = True
try:
res = bool(datetime.strptime(test_str, format))
except ValueError:
res = False
print("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
from dateutil import parser
test_str = '04-01-1997'
print("The original string is : " + str(test_str))
format = "%d-%m-%Y"
res = True
try:
res = bool(parser.parse(test_str))
except ValueError:
res = False
print("Does date match format? : " + str(res))
|
Output:
The original string is : 04-01-1997
Does date match format? : True
Method#3: Using regular expression
Approach
validate a string date format is by using regular expressions. We can define a regular expression pattern that matches the expected format, and then use the re module to check if the string matches the pattern.
Algorithm
1. Import the re module
2. Define the input test string and the regular expression pattern string
3. Use the re.match() method to match the pattern against the test string
4. If the pattern matches the test string:
a. Print “True”
5. Otherwise:
a. Print “False”
Python3
import re
test_str = '04-01-1997'
pattern_str = r'^\d{2}-\d{2}-\d{4}$'
if re.match(pattern_str, test_str):
print("True")
else:
print("False")
|
Time complexity of this approach is O(n), where n is the length of the input string.
Auxiliary Space is also O(n), since we need to store the regular expression pattern in memory.
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...