0

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]
njzk2
  • 38,969
  • 7
  • 69
  • 107
  • Does this answer your question? [Convert timedelta64\[ns\] column to seconds in Python Pandas DataFrame](https://stackoverflow.com/questions/26456825/convert-timedelta64ns-column-to-seconds-in-python-pandas-dataframe) – Ralubrusto Nov 19 '20 at 21:23
  • There no way to do this while preserving the timedelta dtype but you can format these values into a string so that its printed in the format you want. https://stackoverflow.com/questions/538666/format-timedelta-to-string – benji Nov 19 '20 at 22:12

1 Answers1

0

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    Thank you! you have no idea how much you helped me. The first "def" was exactly what I needed to complete my project !! – David soares Nov 20 '20 at 18:22