简体   繁体   中英

Date String in Datetime Format Python

Here is my error I do not manage to solve

ValueError: time data '1/31/2021 22:59' does not match format '%d/%m/%Y %H:%M:%S'

Here is my code 90% of the time my String date I need to convert goes in my try part and It works, I have a problem with my second part.

def StringToDateTime(DateString):
    from datetime import datetime
    try:
        return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
    except:
        DateString = str(DateString)+':00'
        return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

The error you're seeing is due to the str not having a seconds value -- the %S of the datetime format string.

Change the format string so it doesn't have the seconds placeholder, and it should work as expected:

try:
    # Remove the %S from the format string here
    return datetime.strptime(DateString, '%Y-%m-%d %H:%M')

except:
    DateString = str(DateString)+':00'
    return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

Or, if you want to alter the DateString as you do in your except clause:

# Add the seconds to the date string
DateString = f"{DateString}:00"

try:
    return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
    return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM