trying to subtract two datetimes

Viewed 42

Ok so I am trying to subtract the next time from the previous time in a dataframe column called local_time as indicated by this code. I have also tried this using list comprehension.

    next_df = df.shift(-1)
def time_between (df):
    return datetime.combine(date.today(), next_df['Local Time']) - datetime.combine(date.today(), df['Local Time'])
df['time_diff'] = df.apply(time_between, axis = 1)code here

however I recieve this error when trying to subtract:

return datetime.combine(date.today(), next_df['Local Time']) - datetime.combine(date.today(), df['Local Time'])

TypeError: combine() argument 2 must be datetime.time, not Series
1 Answers

You might try if pd.DataFrame.diff will work with datetime data. Assuming your data types are correct, date arithmetic should work fine.

Otherwise, you need to do vectorized calculations using whole arrays as each element in your arithmetic. Also use the dt accessors native to pandas, like pandas.Series.dt.date

instead of date.today(), you can use df['today'] = date.today() and df['today'].dt.date + df['Local Time'].dt.time. 90% sure that will yield a datetime column. If so, you could then use df.diff() pretty easily.

Related