Python字符串转datetime遇ValueError:格式匹配问题求助
问题:datetime字符串转换失败的原因及解决办法
我尝试将程序生成的字符串转换为datetime.datetime对象,但因格式问题转换失败,我认为使用的格式是正确的。相关代码如下:
from datetime import datetime Timer = "27.10.2022 • 08:24:03" Timer = Timer.replace(".", "/") Timer = Timer.replace("•", "", 1) Timer = Timer.replace(" ", "", 1) print(Timer) NewT = datetime.strptime(Timer, "%d/%m/%y %H:%M:%S") print(NewT) print(type(NewT))
执行后输出格式化后的字符串为:27/10/2022 08:24:03,同时触发错误:
ValueError: time data '27/10/2022 08:24:03' does not match format '%d/%m/%y %H:%M:%S'
我看不出问题所在,请问我哪里操作有误?
解决办法
问题出在年份格式符的使用上:
%y对应两位年份(比如22对应2022)%Y对应四位年份(比如2022)
你的格式化后字符串是四位年份2022,但格式串里用了%y,导致格式不匹配。把格式串中的%y改成%Y即可解决:
from datetime import datetime Timer = "27.10.2022 • 08:24:03" # 简化字符串替换步骤 Timer = Timer.replace(".", "/").replace("•", "").strip() print(Timer) NewT = datetime.strptime(Timer, "%d/%m/%Y %H:%M:%S") print(NewT) print(type(NewT))
另外可以简化你的字符串替换逻辑:用strip()一次性去掉首尾多余空格,不用多次调用replace(" ", "", 1),代码更简洁。
内容的提问来源于stack exchange,提问作者mrvn55
相关产品推荐
相关产品推荐

