Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – How to convert timedelta64[ns] to HH:MM:SS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading