How To Calculate Date Difference Between Rows In Pandas

Image for post
Image for post
Photo by Aron Visuals on Unsplash

Problem:

import pandas as pd 
import numpy as np
df = pd.read_excel("GPS Data.xlsx")
df.head(10)
Image for post
Image for post

Solutions:

Image for post
Image for post
df["Start Time"].diff().apply(lambda x: x/np.timedelta64(1, 'm')).fillna(0).astype('int64')
Image for post
Image for post
df["End Time"] - df["Start Time"].shift(1)
Image for post
Image for post
df[["End Time", "Start Time"]] - df[["Start Time", "End Time"]].shift(1)
Image for post
Image for post
(df.loc[:,["Start Time", "End Time"]].sub(df.loc[0,["Start Time", "End Time"]], axis='columns')/np.timedelta64(1, "m")).astype("int64")
Image for post
Image for post
df["End Time"].sub(df["Start Time"].shift(1))

Conclusion:

Written by

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store