'Pandas how to convert time in string to integer? [duplicate]
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.
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 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
