Thursday, December 26, 2024
Google search engine
HomeLanguagesPython – Validate String date format

Python – Validate String date format

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




# Python3 code to demonstrate working of
# Validate String date format
# Using strptime()
from datetime import datetime
 
# initializing string
test_str = '04-01-1997'
 
# printing original string
print("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 value
try:
    res = bool(datetime.strptime(test_str, format))
except ValueError:
    res = False
 
# printing result
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




# Python3 code to demonstrate working of
# Validate String date format
# Using dateutil.parser.parse
from dateutil import parser
 
# initializing string
test_str = '04-01-1997'
 
# printing original string
print("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 value
try:
    res = bool(parser.parse(test_str))
except ValueError:
    res = False
 
# printing result
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")


Output

True

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments