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

如何重置Pandas DataFrame中的时间戳为0起点并累计经过时长

实现代码

先确认time列为pandas datetime类型,再执行以下逻辑即可:

import pandas as pd

# 若time列还不是时间格式,先执行转换
df['time'] = pd.to_datetime(df['time'])

# 计算所有时间与首个时间戳的差值
time_delta = df['time'] - df['time'].iloc[0]
total_seconds = time_delta.dt.total_seconds()

# 拆分出各时间单位后格式化输出
hours = total_seconds // 3600
remaining_seconds = total_seconds % 3600
minutes = remaining_seconds // 60
seconds = remaining_seconds % 60

df['time_new'] = hours.astype(int).astype(str).str.zfill(2) + ":" + \
                 minutes.astype(int).astype(str).str.zfill(2) + ":" + \
                 seconds.apply(lambda x: f"{x:06.3f}")

效果说明

上述代码生成的time_new列完全符合要求:累计小时不会按24小时制截断,同时保留到毫秒级精度,和你给出的示例输出完全匹配。

内容的提问来源于stack exchange,提问作者Adler Müller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:36:04