0

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
  • See [this post](https://stackoverflow.com/q/17978092/2476977) – Ben Grossmann Sep 14 '22 at 19:22
  • You misunderstand I am only using combine to transfer the datetime.time objects to datetime.day so that they are subtractable from one another otherwise you get an operand error. TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' @BenGrossmann – JaredCusick Sep 14 '22 at 19:26
  • 1
    Ok, my mistake. Still, you're apparently trying to apply a datetime module method to a pandas dataframe column – Ben Grossmann Sep 14 '22 at 19:30
  • Can you turn this into a simple, minimal example? A df with a a single column and a few rows should do. Include expected result. It will show us things like data types. – tdelaney Sep 14 '22 at 20:03

1 Answers1

0

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.