strptime() many format 1

strptime() many format

from datetime import datetime

def try_parsing_date(text):
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')

Here is what the above code is Doing:
1. It’s trying to parse the date using the first format in the list.
2. If it fails, it tries the next format in the list.
3. If it fails again, it tries the next format in the list.
4. If it fails again, it raises a ValueError.

Similar Posts