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

如何将特殊字符串格式的时长数据转换为时间/数值格式?

解决Pandas无法识别自定义时长字符串格式的问题

问题说明

现有包含自定义格式时长的数据(第一列为ID,第二列为时长):

1164570    1H45M
1421781        0
458245        7H
2714970       6H
2956491        0
89924          0
580685        3H
1330835    1H45M
599197     6H30M
541245        7H
2257962        0
1418006    1H15M
407282     5H30M
804217     7H30M
1221037    6H30M
1461747        0
148837        3H
168789        2H
2245125       5H
2079324        0
2014516        0
2272373      45M
470768         0
585334     2H45M
163046     2H30M

需要将第二列时长转换为**数值格式(如1小时30分钟转为1.5)**或时间间隔格式,但使用pd.to_datetime(diary_test['time'],format= '%H:%M' ).dt.time时,Pandas无法识别该自定义格式。

解决方案

方法1:转为以小时为单位的数值

通过正则提取小时和分钟数值,计算总时长:

import pandas as pd
import re

def convert_to_hours(duration_str):
    if duration_str == '0':
        return 0.0
    # 匹配小时和分钟数值
    hour_match = re.search(r'(\d+)H', duration_str)
    minute_match = re.search(r'(\d+)M', duration_str)
    hours = int(hour_match.group(1)) if hour_match else 0
    minutes = int(minute_match.group(1)) if minute_match else 0
    return hours + minutes / 60

# 应用函数到目标列
diary_test['hours'] = diary_test['time'].apply(convert_to_hours)

转换后结果示例:1H45M→1.75,45M→0.75,0→0.0。

方法2:转为Pandas Timedelta格式

若需保留时间间隔类型,可转换为Timedelta以支持时间运算:

def convert_to_timedelta(duration_str):
    if duration_str == '0':
        return pd.Timedelta(0)
    # 替换格式为Timedelta可识别的字符串
    timedelta_str = duration_str.replace('H', ' hours ').replace('M', ' minutes')
    return pd.Timedelta(timedelta_str)

diary_test['timedelta'] = diary_test['time'].apply(convert_to_timedelta)

转换后可直接进行时间加减、比较等操作,若需转回小时数值,可使用diary_test['timedelta'].dt.total_seconds() / 3600。

方法3:简洁版转Timedelta

先统一字符串格式,再直接调用pd.to_timedelta:

# 清理格式:将0转为0M,为H/M添加空格适配Timedelta语法
diary_test['clean_time'] = diary_test['time'].replace(
    {'0': '0M', 'H': 'H ', 'M': 'M'}, regex=True
)
# 转换为Timedelta
diary_test['timedelta'] = pd.to_timedelta(diary_test['clean_time'])
# 可选:转为小时数值
diary_test['hours'] = diary_test['timedelta'].dt.total_seconds() / 3600

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:20:31