Ice Storm
Ice Storm

Reputation: 21

When subtracting date columns in pandas and dividing the result by np.timedelta64(1, 'D'), why do I get an error?

I've seen on several questions, such as Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes, the tactic of dividing differences of date columns by np.timedelta64(1,"D").

However, when I attempt such a thing, I get an error of:

TypeError: ufunc true_divide cannot use operands with types dtype('O') and dtype('

Basically, what I'm trying is:

df['time_since_last_change'] = (df['date'] - df['date_of_last_change']) / np.timedelta64(1, 'D')

for two columns of dates/datetimes; I'm wondering if or why they're being viewed as columns of Objects, or why this is considered invalid for use with datetimes?

If anyone could help, it would be very much appreciated; the use of dividing by np.timedelta64 has been mentioned in other answers, but I do not know why it's not working here.

Upvotes: 1

Views: 588

Answers (1)

user3404344
user3404344

Reputation: 1727

use .astype instead of dividing by np.timedelta64

df['time_since_last_change'] = (df['date'] - df['date_of_last_change']).astype('timedelta64[D]')

Upvotes: 1

Related Questions