Search code examples
pythonpandastimedelta

Convert column of seconds to hh:mm:ss - Pandas


I'm sure this is in SO but I can't seem to find it. I'm trying to convert a columnof floats to timestamps displayed as hh:mm:ss. Below is my attempt:

import pandas as pd

d = ({
    'A' : [100.4,200.2,300.3,400.6,500.8,600.9],                 
    'B' : [10.4,21.5,36.3,44.3,56.6,60.5],                                      
     })

df = pd.DataFrame(data = d)

df['A','B'] = pd.to_datetime(df['A','B'], unit='h')

Intended Output:

          A         B
0  00:01:40  00:00:10
1  00:03:20  00:00:22
2  00:05:00  00:00:36
3  00:06:41  00:00:44
4  00:08:21  00:00:57
5  00:10:01  00:01:01

Solution

  • round + pd.to_timedelta, specifying the unit:

    df.round().apply(pd.to_timedelta, unit='s')
    
             A        B
    0 00:01:40 00:00:10
    1 00:03:20 00:00:22
    2 00:05:00 00:00:36
    3 00:06:41 00:00:44
    4 00:08:21 00:00:57
    5 00:10:01 00:01:00
    
    A    timedelta64[ns]
    B    timedelta64[ns]
    dtype: object
    

    You now have the functionality of timedeltas