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

如何将Pandas DataFrame中的字符串列转换为h:mm:ss格式时间?

将DataFrame中的时分秒字符串列转换为时间类型

针对你提到的格式为00:23:44的字符串列,分两种常见场景处理:

场景1:表示一天中的具体时刻(如"00:23:44"是凌晨0点23分44秒)

直接用pandas.to_datetime解析字符串,再提取time属性得到标准时间类型:

import pandas as pd

# 替换成你的DataFrame名称和目标列名
df['time_col'] = pd.to_datetime(df['time_col'], format='%H:%M:%S').dt.time

指定format='%H:%M:%S'能让解析更高效,避免pandas自动推断格式时出现偏差。

场景2:表示时间段(如"00:23:44"是持续23分44秒的时长)

如果是时长类数据,转成timedelta类型更适配后续的时长运算(比如加减、统计):

df['duration_col'] = pd.to_timedelta(df['duration_col'])

额外提示

如果列中存在格式无效的字符串,可添加errors='coerce'参数,将无效值转为NaT(缺失值),避免程序中断:

# 时刻场景处理无效值
df['time_col'] = pd.to_datetime(df['time_col'], format='%H:%M:%S', errors='coerce').dt.time

# 时长场景处理无效值
df['duration_col'] = pd.to_timedelta(df['duration_col'], errors='coerce')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:45:35