1

I have a time variable in my dataframe and I am trying to come up with a new column that gives the time passed in minutes from one row to another. I was trying to use this function:

df["Time"].diff()

But I get the following error:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

Is there any way I can create a column in pandas with the time difference from one row to the next one?

2

1 Answer 1

2

You can convert Time column to datetimes with default same date, so Series.diff working well:

df['difference'] = pd.to_datetime(df["Time"].astype(str)).diff()
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain why that should work? How can diff() work on a datetime.time type once converted to string?
I tried it and it worked perfectly thank you! had to modify a bit to have it as a new column, but thank you very much
@NataliaCaceres - You are welcome, code is edited for assign to column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.