You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用strptime解析时间出现unconverted data remains错误如何解决

报错原因

Python datetime 模块的 strptime 方法中,%f 格式符专门用于匹配微秒部分,仅支持最多6位数字。你使用的时间字符串 00:00:49.9342733 小数点后有7位数字,%f 匹配前6位后还剩余最后1位 3 无法被解析,因此触发unconverted data remains报错。

修复方案

方案1:预处理截断多余的微秒位

在解析前对时间字符串做处理,微秒部分仅保留前6位即可,兼容微秒位数不足6位的场景:

from datetime import datetime

s = "00:00:49.9342733"
if "." in s:
    main_part, micro_part = s.split(".", 1)
    s = f"{main_part}.{micro_part[:6]}"

duration = datetime.strptime(s, "%H:%M:%S.%f")

方案2:固定切片移除多余字符

如果你的时间字符串格式固定都是小数点后7位,也可以直接切片切掉最后1位冗余字符:

from datetime import datetime

s = "00:00:49.9342733"
duration = datetime.strptime(s[:15], "%H:%M:%S.%f")

内容的提问来源于stack exchange,提问作者Jannat Arora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:15:03