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 time in string to integer?

I have pandas Series (column) of time in string. I am interested in time but I need it in to convert to integer or float.

here is my dataframe:

 df = pd.DataFrame({'time': ['00:04:01.2540000', '00:02:17.6700000', '00:03:31.6830000',
       '00:03:28.5670000', '00:01:50.6770000', '00:02:26.0170000',...], ...} 

In the time column is in string. If I convert to by pd.to_datetime() it makes me date(it’s ok) by if I tried to convert to number I got time in Unix something like 1651050829.
And I wasn’t able to figured out how to get just the time.

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

I am interested just in time in seconds. For example the first is 4 minutes and 1 seconds so desired results is 241 seconds.

>Solution :

Use pd.to_timedelta(df['time']).dt.total_seconds().

Demo:

>>> df = pd.DataFrame({'time': ['00:04:01.2540000', '00:02:17.6700000']})
>>> df 
               time
0  00:04:01.2540000
1  00:02:17.6700000
>>> pd.to_timedelta(df['time']).dt.total_seconds() 
0    241.254
1    137.670
Name: time, dtype: float64

edit: chain an .astype(int) if you want to truncate the decimal places.

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