How to check if a date is in a specified format is a common task in programming languages, and Python is no exception. In this tutorial, we will learn how to check if a date is in the MM/dd/yyyy format in Python.
We will make use of Python’s built-in library “datetime” to accomplish this task. Follow the steps below, and you will be able to validate the date format.
Step 1: Import the datetime library
First, we need to import Python’s datetime library, which will provide us with the tools necessary to work with dates. Add the following line at the beginning of your Python script to import the datetime module:
1 |
from datetime import datetime |
Step 2: Create a sample date
Next, we will create a sample date string to test if it is in MM/dd/yyyy format. For this tutorial, we’ll use the date “08/25/2021”. Assign this string to a variable, like this:
1 |
date_string = "08/25/2021" |
Step 3: Define a function to check the date format
Now let’s create a function named is_in_format
that will take the date string as input and return True if the date is in MM/dd/yyyy format, and False otherwise.
1 2 3 4 5 6 |
def is_in_format(date_string): try: datetime.strptime(date_string, "%m/%d/%Y") return True except ValueError: return False |
Inside the is_in_format
function, we use the strptime
method of the datetime
class to try to parse the date string according to the given format (MM/dd/yyyy). If the parsing is successful, it means the date string is in the desired format, and the function returns True. If parsing fails, it raises a ValueError
exception and the function returns False.
Step 4: Test the function
Now that we have defined our is_in_format
function, it’s time to test it with the sample date string we created earlier. Call the function with the date_string
variable as an argument, like this:
1 |
result = is_in_format(date_string) |
Then, print the result:
1 |
print(f"The date string {date_string} is in MM/dd/yyyy format: {result}") |
You should see the following output:
The date string 08/25/2021 is in MM/dd/yyyy format: True
Full code
1 2 3 4 5 6 7 8 9 10 11 12 |
from datetime import datetime def is_in_format(date_string): try: datetime.strptime(date_string, "%m/%d/%Y") return True except ValueError: return False date_string = "08/25/2021" result = is_in_format(date_string) print(f"The date string {date_string} is in MM/dd/yyyy format: {result}") |
Output
The date string 08/25/2021 is in MM/dd/yyyy format: True
Conclusion
In this tutorial, we learned how to check if a date string is in the MM/dd/yyyy format using Python’s datetime library. The is_in_format
function we defined can be reused to validate other date strings efficiently, helping you avoid incorrect data inputs and improving the reliability of your Python applications.