Pandas | How to get the time difference in seconds between two columns that contain timestamps

Viewed 6109

I have two columns that both contain times and I need to get the difference of the two times. I would like to add the difference of each row timestamps to a new column "time_diff". The times are only going to be 10-30 seconds apart so I need the time_diff column to be a difference in the seconds(like this format 00:00:07).

I'm really struggling with this its for my work and it is a bit out of my element. Greatly appreciate all of the answers.

Example of the format of the two columns

start_time | end_time


00:06:34 00:06:45

00:06:59 00:07:02

00:07:36 00:07:34

3 Answers

First convert these into datetime format as given below:

df['start'] = pd.to_datetime(df['start'])
df['end'] = pd.to_datetime(df['end'])

Then, you can perform subtract operations:

df['diff'] = df['end']-df['start']

This will give you answer in HH:MM:SS

In case you want to find answers only in seconds (it will give output in total seconds of difference)

df['diff'] = (df['end']-df['start']).dt.total_seconds()

Similar to @Dhiraj

df["time_diff"] = pd.to_datetime(df["end_time"]) - pd.to_datetime(df["start_time"])

df["time_diff_secs"] = (pd.to_datetime(df["end_time"]) - pd.to_datetime(df["start_time"])).dt.total_seconds()

OUTPUT->

   start_time end_time         time_diff  time_diff_secs
0   00:06:34  00:06:45          00:00:11            11.0
1   00:06:59  00:07:02          00:00:03             3.0
2   00:07:36  00:07:34 -1 days +23:59:58            -2.0
Related