Python strptime multiple formats

Python strptime with multiple formats

The strptime() function in Python is used to parse a string representing a date or time and convert it into a datetime object. It takes two arguments – the string to parse and a format string specifying the expected format of the input string.

In some cases, you may have strings with different formats that need to be parsed. To handle multiple formats, you can provide a list of format strings to the strptime() function and it will attempt to match each format until a successful parse is found.

Here’s an example:


import datetime

date_strings = ["2022-01-01", "01/01/2022", "Jan 1, 2022"]

for date_string in date_strings:
    try:
        date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
        print(f"Successfully parsed {date_string} using format %Y-%m-%d")
    except ValueError:
        pass

    try:
        date_object = datetime.datetime.strptime(date_string, "%d/%m/%Y")
        print(f"Successfully parsed {date_string} using format %d/%m/%Y")
    except ValueError:
        pass

    try:
        date_object = datetime.datetime.strptime(date_string, "%b %d, %Y")
        print(f"Successfully parsed {date_string} using format %b %d, %Y")
    except ValueError:
        pass
    

In this example, we have a list of date strings with different formats. We iterate over each string and try to parse it using multiple format strings. If a format string is successful, we print a success message indicating the format that was used.

The strptime() function throws a ValueError if the input string doesn’t match the specified format. In the example, we catch this exception and do nothing, effectively skipping that format if it fails.

This way, you can parse date strings with different formats using the strptime() function in Python.

Leave a comment