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?
JavaScript
x
6
1
Tipo
2
Displacement 56 days 04:36:02
3
Idleness 66 days 17:27:10
4
Productivity 252 days 05:52:20
5
Name: Invested time, dtype: timedelta64[ns]
6
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:
JavaScript
1
31
31
1
import pandas as pd
2
3
df = pd.DataFrame({"td": pd.to_timedelta(["56 days 04:36:02","66 days 17:27:10","252 days 05:52:20"])})
4
5
def td_to_hmsstr(td):
6
"""
7
convert a timedelta object td to a string in HH:MM:SS format.
8
"""
9
hours, remainder = divmod(td.total_seconds(), 3600)
10
minutes, seconds = divmod(remainder, 60)
11
return f'{int(hours):02}:{int(minutes):02}:{int(seconds):02}'
12
13
df['H:M:S'] = df['td'].apply(td_to_hmsstr)
14
15
def td_to_hmstuple(td):
16
"""
17
convert a timedelta object td to a tuple (hours, minutes, seconds).
18
"""
19
hours, remainder = divmod(td.total_seconds(), 3600)
20
minutes, seconds = divmod(remainder, 60)
21
return tuple(map(int, (hours, minutes, seconds)))
22
23
df = pd.concat([df, pd.DataFrame(df['td'].apply(td_to_hmstuple).to_list(),
24
columns=['hours', 'minutes', 'seconds'])], axis=1)
25
26
df
27
# td H:M:S hours minutes seconds
28
# 0 56 days 04:36:02 1348:36:02 1348 36 2
29
# 1 66 days 17:27:10 1601:27:10 1601 27 10
30
# 2 252 days 05:52:20 6053:52:20 6053 52 20
31