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

如何在Pandas中将分秒毫秒格式列转换为秒或毫秒单位?

如何在Pandas中将分.秒.毫秒格式的时间转换为秒/毫秒单位?

嘿,这个问题我之前处理过!你的time列是分.秒.毫秒的非标准格式(比如3.05.3代表3分5秒3毫秒),strptime确实可以用,但直接拆分字符串计算可能更直观,下面给你两种可行的实现方法:

首先先构造示例数据,方便我们演示:

import pandas as pd

data = {
    'Runner': ['A', 'B'],
    'time': ['3.05.3', '2.50.2']
}
df = pd.DataFrame(data)

方法一:直接拆分字符串计算(推荐,简单直观)

这种方法不需要依赖时间格式化函数,直接按分隔符拆分后做数值计算,非常适合这种明确的分段格式:

# 将time列按`.`拆分为分钟、秒、毫秒三列,并转换为整数类型
df[['minutes', 'seconds', 'milliseconds']] = df['time'].str.split('.', expand=True).astype(int)

# 计算总秒数:分钟转秒 + 秒 + 毫秒转秒
df['total_seconds'] = df['minutes'] * 60 + df['seconds'] + df['milliseconds'] / 1000

# 计算总毫秒数:分钟转毫秒 + 秒转毫秒 + 毫秒
df['total_milliseconds'] = df['minutes'] * 60 * 1000 + df['seconds'] * 1000 + df['milliseconds']

执行后你的DataFrame会变成这样:

Runnertimeminutessecondsmillisecondstotal_secondstotal_milliseconds
A3.05.3353185.003185003
B2.50.22502170.002170002

方法二:使用strptime(适合后续有更多时间操作的场景)

如果你后续需要对时间做更多复杂操作(比如时间差计算),可以用strptime,但需要先把格式转换成它能识别的样式:

# 把time列的第一个`.`替换成`:`,变成`%M:%S.%f`能识别的格式(比如`3.05.3`→`3:05.3`)
df['formatted_time'] = df['time'].str.replace('.', ':', n=1)

# 转换为datetime对象,指定格式为「分钟:秒.毫秒」
df['time_obj'] = pd.to_datetime(df['formatted_time'], format='%M:%S.%f')

# 计算总秒数:注意datetime对象默认会带一个起始日期,所以要减去当天0点的秒数
base_time = pd.to_datetime('1900-01-01')
df['total_seconds'] = df['time_obj'].dt.total_seconds() - base_time.total_seconds()

# 转换为总毫秒数
df['total_milliseconds'] = df['total_seconds'] * 1000

这个方法最终得到的结果和方法一完全一致,只是多了datetime对象,方便后续的时间相关操作。

两种方法都能满足你的需求,你可以根据自己的实际场景选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:33:49