首页 > 解决方案 > 日期时间格式 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')

标签: pythondatetime

解决方案


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

推荐阅读