Search code examples
pythonpython-3.xdatetimestrptime

Python Convert to %Y-%m-%d %H:%M With Different Length Strings


I want to convert a string in one of the possible formats (%d.%m.%Y %H:%M OR %d.%m.%Y %H:%M:%S OR %d.%m.%Y) to %Y-%m-%d %H:%M

At present i am using the following code:

newMessageDate = log.get('messageDate')
        try:
            newMessageDate = datetime.datetime.strptime(newMessageDate,'%d.%m.%Y %H:%M').strftime('%Y-%m-%d %H:%M')
        except ValueError:
            newMessageDate = datetime.datetime.strptime(newMessageDate,'%d.%m.%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') 

It works fine if the String is in either %d.%m.%Y %H:%M OR %d.%m.%Y %H:%M:%S but I'm not sure how to add the 3rd format. I tried adding it as an except but it never gets triggered.

Am I on the right track or is there a better way to do this?

Thanks


Solution

  • You can make a list of possible formats and try them one by one.

    date_formats = ["%d.%m.%Y %H:%M", "%d.%m.%Y %H:%M:%S", "%d.%m.%Y", "%d.%m.%Y %H:%M"]
    for date_fmt in date_formats:
        try:
            newMessageDate = datetime.datetime.strptime(newMessageDate, date_fmt).strftime('%Y-%m-%d %H:%M')
        except ValueError:
            continue
        else:
            break