日期时间格式的日期字符串 Python

时间:2021-02-01 17:50:09

标签: python datetime

这是我无法解决的错误

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

这是我的代码 我需要转换的字符串日期有 90% 的时间出现在我的 try 部分并且它有效,但我的第二部分有问题。

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')

1 个答案:

答案 0 :(得分:0)

您看到的错误是由于 str 没有秒值 - 日期时间格式字符串的 %S

更改格式字符串,使其没有秒占位符,它应该可以按预期工作:

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')

或者,如果您想像在 DateString 子句中那样更改 except

# 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')