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

Calculate time difference in seconds in pandas

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

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 :

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