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

如何将hh:mm:ss格式列转为秒并计算DataFrame各状态耗时?

计算DataFrame中各系统状态的耗时及时间格式转换方案

不需要手动计算,用Pandas可以完全自动化处理你的需求,下面分两部分解决你的问题:

一、将"hh:mm:ss"格式转换为总秒数

你之前的代码df['time'] = df['time'].dt.strftime(%S)有两个问题:一是strftime的格式字符串需要用引号包裹,二是%S仅提取时间中的秒数部分(0-59),并非从0点开始的总秒数。

正确的转换方法分两步:

  1. 先将字符串类型的时间转为Pandas的时间对象:
import pandas as pd
df['time'] = pd.to_datetime(df['time'], format='%H:%M:%S')
  1. 计算总秒数,有两种方式:
  • 手动计算(直观):
df['total_seconds'] = df['time'].dt.hour * 3600 + df['time'].dt.minute * 60 + df['time'].dt.second
  • 用Pandas内置方法(简洁):
df['total_seconds'] = df['time'].dt.total_seconds()

两种方式得到的结果一致,都是从当天00:00:00开始累计的秒数(比如12:30:05会转换成(12*60+30)*60+5 = 45005)。

二、计算每个系统状态的耗时

你的数据当前是按时间倒序排列的(示例中high的时间晚于low),首先需要按时间升序排序,再对连续相同的状态分组计算耗时:

  1. 按时间升序排序:
df = df.sort_values(by='time', ascending=True).reset_index(drop=True)
  1. 标记连续相同状态的分组:
df['group_id'] = (df['System state'] != df['System state'].shift()).cumsum()
  1. 分组计算每个状态段的耗时:
state_duration = df.groupby(['System state', 'group_id']).agg(
    start_time=('time', 'min'),
    end_time=('time', 'max'),
    duration_seconds=('total_seconds', lambda x: x.max() - x.min())
).reset_index()

最终state_duration会包含每个连续状态段的开始/结束时间,以及持续的秒数。如果需要按状态汇总总耗时,可以再做一次分组:

total_state_duration = state_duration.groupby('System state')['duration_seconds'].sum().reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:12:50