0 votes
in Python by
How would you validate a date string in Python?

1 Answer

0 votes
by

To validate a date string in Python, the datetime module can be used. This module has a method called strptime() which is used to convert a string into a datetime object. If the string is not a valid date, this method will raise a ValueError exception.

Here’s an example of how you could use it:

from datetime import datetime
def validate_date(date_string):
try:
datetime.strptime(date_string, '%Y-%m-%d')
return True
except ValueError:
return False

In this code, ‘%Y-%m-%d’ is the format for the date. It means that the date should be in the form ‘YYYY-MM-DD’. If the date_string does not match this format, strptime() will raise a ValueError and the function will return False. Otherwise, it returns True indicating the date_string is valid.

Related questions

0 votes
asked Dec 22, 2023 in C Plus Plus by GeorgeBell
0 votes
asked Aug 22, 2022 in Python by Robindeniel
...