Skip to content
Related Articles

Related Articles

Improve Article

Python – Validate String date format

  • Last Updated : 11 Aug, 2021

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :