pandas转换多格式字符串时间为时间对象时报格式匹配错误如何解决
报错原因
你指定的%H:%M:%S格式要求时间字符串必须包含「时:分:秒」三个部分,但你的数据中存在仅包含「分:秒」的字符串(如49:49),格式不匹配导致转换失败。
解决方案
方案1:统一补全时间格式后转换
先对时间字符串做预处理,只有1个冒号的字符串自动补全小时位为0:
import pandas as pd df_plot2 = df[['year', 'gun_time', 'chip_time']].copy() # 加copy避免链式赋值警告 # 定义补全时间的函数 def fill_time(t_str): if t_str.count(':') == 1: return f'0:{t_str}' return t_str # 先处理列再转换 df_plot2['gun_time'] = pd.to_datetime(df_plot2['gun_time'].apply(fill_time), format='%H:%M:%S').dt.time df_plot2['chip_time'] = pd.to_datetime(df_plot2['chip_time'].apply(fill_time), format='%H:%M:%S').dt.time
方案2:转换为timedelta类型(适配耗时场景)
你的数据属于比赛耗时类场景,用pd.to_timedelta更适配,会自动识别两种格式,不需要手动补全,转换后可直接做加减、求平均等耗时统计:
df_plot2 = df[['year', 'gun_time', 'chip_time']].copy() df_plot2['gun_time'] = pd.to_timedelta(df_plot2['gun_time']) df_plot2['chip_time'] = pd.to_timedelta(df_plot2['chip_time'])
方案3:自动推断格式(不推荐,存在歧义风险)
不指定format参数,让pandas自动适配格式,但特殊格式下可能出现识别错误:
df_plot2 = df[['year', 'gun_time', 'chip_time']].copy() df_plot2['gun_time'] = pd.to_datetime(df_plot2['gun_time']).dt.time df_plot2['chip_time'] = pd.to_datetime(df_plot2['chip_time']).dt.time
内容的提问来源于stack exchange,提问作者Daniel Grillo
相关产品推荐
相关产品推荐

