简体   繁体   中英

Display pandas timedelta in HH:MM:SS format by converting days to hours

If I use

first_an_last['duration'] = (first_an_last.last_time - first_an_last.first_time)

I get

0       0 days 04:19:00
1       2 days 04:39:00
2       1 days 06:10:00

Which is fine, but I want to display this:

0       04:19:00
1       52:39:00
2       30:10:00

Of course I can have this:

first_an_last['duration'] = (first_an_last.last_time - first_an_last.first_time) / pd.Timedelta(hours=1)

where I can get

0        4.316667
1        52.650000
2        30.166667

But I would like to display it formatted as HH:MM:SS regardless of the number of hours as the user do not understand how much minutes (and seconds) is 0.65 hour in this example

Try this

def converter(x):
    hour = x.hour + (x.days * 24)
    hour = hour if hour > 9 else "0"+str(hour)
    minutes = x.minutes if minutes > 9 else "0"+str(minutes)
    seconds = x.seconds if minutes > 9 else "0"+str(seconds)
    return f"{hour}:{minutes}:{seconds}"

Considering the column first_an_last['duration'] is in timedelta format

first_an_last['duration'] = first_an_last['duration'].apply(lambda x: converter(x.components)

if first_an_last['duration'] is not timedelta format, try below one

first_an_last['duration'] = first_an_last['duration'].apply(lambda x: converter(pd.to_timedelta(x).components)

Let me know your results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM