Skip to content
Advertisement

Convert result of sum of timedeltas in Python

I have the output below from a sum of a timedelta list in a column on my dataframe. How do I get values converted to hours minutes and total seconds?

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]

Advertisement

Answer

afaik, there’s no built-in functionality for this. But you can create your own. For example for formatting to a string in H:M:S format or splitting the timedelta into separate columns hours, minutes and seconds. Ex:

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement