You need to enable JavaScript to run this app. Python Pandas时间列格式转换及pd.to_datetime匹配错误解决
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas时间列格式转换及pd.to_datetime匹配错误解决

错误原因

str.strip()是按字符集匹配移除首尾字符,不是匹配固定前缀。你传入的'00:'会让方法把字符串首尾所有的0和:都删掉,比如00:01:24处理后就变成了1:24,不符合后续格式匹配要求。

解决方案

有两种常用的实现方式:

方法1:直接拆分原时间字符串拼接

原时间是%H:%M:%S格式,你需要的结果刚好是取原时间的分、秒作为新时间的时、分,末尾补00秒,直接拆分拼接即可:

# 按冒号拆分时间列,取第1、2位索引(对应原时分秒结构的分、秒),拼接后补:00
df['time'] = df['time'].str.split(':', expand=True).apply(lambda x: f"{x[1]}:{x[2]}:00", axis=1)
# 如果需要转成datetime的time类型,再加下面这行
df['time'] = pd.to_datetime(df['time'], format="%H:%M:%S").dt.time

方法2:用正则替换固定前缀

如果你要删除前缀的逻辑实现,应该用str.replace匹配开头的00:,而不是strip:

# 仅替换字符串开头的00:前缀
df['time'] = df['time'].str.replace(r'^00:', '', regex=True)
# 末尾补:00得到目标格式
df['time'] = df['time'] + ':00'
# 转time类型按需添加
df['time'] = pd.to_datetime(df['time'], format="%H:%M:%S").dt.time

两种方法都可以得到你需要的01:24:00格式结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 17:45:10