To check the input format of a date in Python, you can use the datetime module. The datetime module provides various functions for working with dates and times in Python.
Here’s an example code snippet to check the input format of a date in Python:
from datetime import datetime
date_string = input("Enter a date in the format DD/MM/YYYY: ")
try:
datetime.strptime(date_string, '%d/%m/%Y')
print("Valid date format!")
except ValueError:
print("Invalid date format!")
In this example, we first import the datetime module. We then ask the user to enter a date in the format DD/MM/YYYY and store the input in the variable date_string.
We then use a try-except block to attempt to convert the input string to a datetime object using the strptime function. The strptime function takes two arguments – the input string and the expected format of the date.
In this case, we expect the input string to be in the format DD/MM/YYYY, so we use ‘%d/%m/%Y’ as the expected format. If the input string is in the correct format, the strptime function will return a datetime object, and we print “Valid date format!”.
If the input string is not in the correct format, the strptime function will raise a ValueError exception, and we print “Invalid date format!”.
You can modify the format string to match the expected input format of your date. If the input format is different from the expected format, the code will raise a ValueError and print “Invalid date format!”.
+ There are no comments
Add yours