Home > Blockchain >  Pandas - How to convert timedelta64[ns] to HH:MM:SS
Pandas - How to convert timedelta64[ns] to HH:MM:SS

Time:02-16

I have a doubt how can I convert all column from Pandas (Python) from timedelta64[ns] like: 2 days 03:29:05 to: 51:29:05.

**PLEASE, CONSIDER time COLUMN AS A timedelta64[ns]**

d = {'id': [1123, 2342], 'time': ['2 days 03:29:05', '1 days 01:57:53']}

df = pd.DataFrame(data=d)
df['time'] = pd.to_timedelta(df['time'])

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


df.info()

Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   id      2 non-null      int64 
 1   time    2 non-null      timedelta64[ns]
dtypes: int64(1), timedelta64[ns](1)

And 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

CodePudding user response:

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()]

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
  • Related