在 Python 中转换时间增量总和的结果

Convert result of sum of timedeltas in Python

我的数据框的一列中的 timedelta 列表的总和输出如下。如何将值转换为小时分钟和总秒数?

Tipo
Displacement     56 days 04:36:02
Idleness         66 days 17:27:10
Productivity     252 days 05:52:20
Name: Invested time, dtype: timedelta64[ns]

afaik,没有内置的功能。但是您可以创建自己的。例如,用于格式化为 H:M:S 格式的字符串或将 timedelta 拆分为单独的列小时、分钟和秒。例如:

import pandas as pd

df = pd.DataFrame({"td": pd.to_timedelta(["56 days 04:36:02","66 days 17:27:10","252 days 05:52:20"])})

def td_to_hmsstr(td):
    """
    convert a timedelta object td to a string in HH:MM:SS format.
    """
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    return f'{int(hours):02}:{int(minutes):02}:{int(seconds):02}'

df['H:M:S'] = df['td'].apply(td_to_hmsstr)

def td_to_hmstuple(td):
    """
    convert a timedelta object td to a tuple (hours, minutes, seconds).
    """
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    return tuple(map(int, (hours, minutes, seconds)))

df = pd.concat([df, pd.DataFrame(df['td'].apply(td_to_hmstuple).to_list(), 
                                 columns=['hours', 'minutes', 'seconds'])], axis=1)

df
#                  td       H:M:S  hours  minutes  seconds
# 0  56 days 04:36:02  1348:36:02   1348       36        2
# 1  66 days 17:27:10  1601:27:10   1601       27       10
# 2 252 days 05:52:20  6053:52:20   6053       52       20