pythonpandastimedelta

How to convert timedelta to HH:MM:SS


How can I convert a column from timedelta64[ns] like 2 days 03:29:05 to 51:29:05?

data = {'id': [1123, 2342], 'time': ['2 days 03:29:05', '1 days 01:57:53']}
df = pd.DataFrame(data)
df['time'] = pd.to_timedelta(df['time'])
     id             time
0  1123  2 days 03:29:05
1  2342  1 days 01:57:53

I would like to add a new column as:

   id               time       new
0  1123  2 days 03:29:05  51:29:05
1  2342  1 days 01:57:53  25:57:53

Solution

  • I don't think that there is a direct way. But you could use a custom function on top of total_seconds:

    def sec_to_format(s):
        h, s = divmod(int(s), 3600)
        m, s = divmod(s, 60)
        return f'{h:02}:{m:02}:{s:02}'
    
    df['time_str'] = [sec_to_format(s) for s in df['time'].dt.total_seconds()]
    

    For a vectorial approach:

    def vect_delta_to_hms(s):
        s = s.dt.total_seconds().astype('Int64')
        h, s = s.divmod(3600)
        m, s = s.divmod(60)
        return (h.astype(str).str.zfill(2)
                + ':' + m.astype(str).str.zfill(2)
                + ':' + s.astype(str).str.zfill(2)
               ).mask(s.isna())
    
    df['time_str'] = vect_delta_to_hms(df['time'])
    

    output:

         id            time  time_str
    0  1123 2 days 03:29:05  51:29:05
    1  2342 1 days 01:57:53  25:57:53