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

如何将Pandas DataFrame中的时间格式列转换为分钟/秒数值?

将Pandas中的时分秒格式转换为总分钟/秒数的方法

嘿,这个需求在做回归分析时太常见了——得把时分秒的时间格式转成纯数值(分钟/秒数)才能作为自变量使用。我给你分享两种靠谱的方法,第一种是Pandas原生的简便方案,第二种适合格式完全固定时手动计算:

方法一:用pd.to_timedelta()快速转换(推荐)

Pandas的to_timedelta()函数可以直接把你的时分秒字符串转成时间差类型,之后就能轻松提取总秒数/分钟数,代码简洁还能兼容多种合法时间格式:

import pandas as pd

# 假设你的DataFrame是df,时间列名为'time_duration'
df['time_delta'] = pd.to_timedelta(df['time_duration'])

# 转换为总分钟数
df['total_minutes'] = df['time_delta'].dt.total_seconds() / 60

# 或者直接得到总秒数(适合更精细的分析)
df['total_seconds'] = df['time_delta'].dt.total_seconds()

如果你的数据里有格式错误的异常值,可以加上errors='coerce'参数,把非法值转为NaT(类似NaN的时间类型),方便后续清洗:

df['time_delta'] = pd.to_timedelta(df['time_duration'], errors='coerce')

方法二:手动拆分字符串计算(适合格式绝对固定的场景)

如果你的时间列格式完全是时:分:秒没有例外,可以直接拆分字符串后手动计算,这种方式更直观:

# 拆分时分秒为三列,转成整数类型
df[['hours', 'minutes', 'seconds']] = df['time_duration'].str.split(':', expand=True).astype(int)

# 计算总分钟数(保留秒数的小数部分)
df['total_minutes'] = df['hours'] * 60 + df['minutes'] + df['seconds'] / 60

# 计算总秒数
df['total_seconds'] = df['hours'] * 3600 + df['minutes'] * 60 + df['seconds']

两种方法都能得到你需要的数值型时长变量,之后就可以直接用这个新列做线性回归分析啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:26:54