繁体   English   中英

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

[英]Date String in Datetime Format Python

这是我无法解决的错误

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

您看到的错误是由于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')

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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