Skip to content
Advertisement

Duration between two timestamps

I have a dataframe with different timestamp for each user, and I want to calculate the duration. I used this code to import my CSV files:

JavaScript

df.head()

JavaScript

And I want to get something like that

JavaScript

I’ve used this code, but doesn’t work for me

JavaScript

Advertisement

Answer

Operations which occur over groups of values are GroupBy operations in pandas.

pandas supports mathematical operations over timestamps natively. For this reason, subtraction will give the correct duration between any two timestamps.

We’ve already successfully converted out timestamp column to datetime64[ns]

JavaScript

Now we can take the difference between rows within groups with Groupby.diff

JavaScript

df

JavaScript

If we want to get the duration in seconds we can extract the total number of seconds using Series.dt.total_seconds:

JavaScript

df:

JavaScript

Complete Working Example:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement