I have a pandas DataFrame with a datetime column (‘time’) in m/d/yyyy h:mm:ss format. I need to calculate the difference between each row and the previous row and display the result in a new column (‘SEC’) in seconds.
For example:
time SEC
4/18/2023 2:43:00
4/18/2023 3:13:00 1800
4/18/2023 3:35:53 1373
4/18/2023 3:36:03 10
>Solution :
Use diff
+ .dt.total_seconds
(ty @QuangHoang)
df['time'].diff().dt.total_seconds
If your time
column is not yet a datetime64
dtype, you can do
df['time'] = pd.to_datetime(df['time'], format='%m/%d/%Y %H:%M:%S')
df['time'].diff().dt.total_seconds