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

如何用Python正确解析时长数据:纠正分钟与小时格式混淆问题

解决时间格式转换问题

问题分析

你的数据里存在两种时长格式:

  • 32:43:00 → 代表32分43秒(而非32小时43分)
  • 1:00:10/1:07:41 → 代表1小时0分10秒、1小时7分41秒
    Excel里的显示差异是因为Excel会把超过24小时的时长自动转成日期时间格式,但我们需要按业务规则手动解析。

解决方案

编写自定义解析函数,区分两种格式后转换为标准时长,再格式化输出:

import pandas as pd

def parse_race_time(s):
    # 分割时间字符串为三个部分
    parts = s.strip().split(':')
    if len(parts) != 3:
        return pd.NaT  # 处理异常格式
    
    hh, mm, ss = parts
    # 判断格式:如果秒数为00,且第一部分数值过大(不符合正常小时范围),则按分:秒:00处理
    if ss == '00' and int(hh) > 10:  # 阈值可根据实际业务调整
        # 格式为 分钟:秒:00 → 转换为0小时+hh分钟+mm秒
        total_seconds = int(hh)*60 + int(mm)
    else:
        # 格式为 小时:分钟:秒 → 正常转换
        total_seconds = int(hh)*3600 + int(mm)*60 + int(ss)
    
    return pd.to_timedelta(total_seconds, unit='s')

# 应用函数到Time列
df['Time'] = df['Time'].apply(parse_race_time)

# 格式化输出为hh:mm:ss格式
def format_timedelta(td):
    total_seconds = int(td.total_seconds())
    hours = total_seconds // 3600
    remaining = total_seconds % 3600
    minutes = remaining // 60
    seconds = remaining % 60
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"

df['Formatted_Time'] = df['Time'].apply(format_timedelta)

print(df)

代码说明

  1. parse_race_time函数:
    • 分割字符串后,通过秒数是否为00和第一部分数值是否超出合理小时范围(示例设为10,可根据你的数据调整)区分两种格式
    • 计算总秒数后转换为timedelta类型,保证后续计算的准确性
  2. format_timedelta函数:
    • 由于timedelta没有直接的strftime方法,手动计算小时、分钟、秒并格式化为两位数字的hh:mm:ss格式
  3. 最终生成Formatted_Time列存储格式化后的结果,保留原Time列的timedelta类型方便后续分析

注意事项

  • 如果业务中存在小时数超过10的合理场景,可将阈值调整为24(即当第一部分≥24时按分钟处理)
  • 若有异常格式(比如不是三个部分的字符串),函数会返回NaT,可后续用df.dropna()或填充默认值处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:24:59