1

I have a column in a pandas dataframe in seconds.

   seconds
0   122400
1    43245
2   234143
3    53245
4   394911

I want to convert that into HH:MM:SS and I do not want days. Instead, I want the day to be added into hours.

   seconds       time
0   122400   34:00:00
1    43245   12:00:45
2   234143   65:02:23
3    53245   14:47:25
4   394911  109:41:51

For example, if it was 1 day 10:00:00, I need to output to be 34:00:00.

BeRT2me
  • 12,699
  • 2
  • 13
  • 31
SasLNat
  • 33
  • 3
  • `df['time'] = pd.to_timedelta(df.seconds, unit='s')` `df['time'] = (x.days.mul(24).add(x.hours).astype(str).str.zfill(2) + ':' + x.minutes.astype(str).str.zfill(2) + ':' + x.seconds.astype(str).str.zfill(2))` – BeRT2me Jul 20 '22 at 03:17
  • The supposed duplicates do not answer the question in a pandas friendly way and should not count as duplicates. – BeRT2me Jul 20 '22 at 03:18

1 Answers1

2

You can use a series of divmod then convert to zero padded strings:


m,s = df['s'].divmod(60)
h,m = m.divmod(60)

df['time'] = (h.astype(str).str.zfill(2)+':'+
              m.astype(str).str.zfill(2)+':'+
              s.astype(str).str.zfill(2)
              )

Example:

        s      time
0       9  00:00:09
1    1439  00:23:59
2   86399  23:59:59
3  108000  30:00:00

as a function

def s_to_hms(s):
    m,s = s.divmod(60)
    h,m = m.divmod(60)
    return (h.astype(str).str.zfill(2)+':'+
            m.astype(str).str.zfill(2)+':'+
            s.astype(str).str.zfill(2)
           )

df['time'] = s_to_hms(df['s'])
mozway
  • 194,879
  • 13
  • 39
  • 75