Mehdi
Mehdi

Reputation: 1296

time difference with Timedelta gives wrong result

I am using python to calculate the time difference in hour. However, I get wrong result. Here is my code and I get 18.4 hour but the answer shoube be much more definitely!

import pandas as pd
from datetime import timedelta
t1 = pd.to_datetime('2016-12-15 16:39:46')
t2 = pd.to_datetime('2016-12-21 11:03:59')
print(pd.Timedelta(t2 - t1).seconds/3600.0)

Upvotes: 2

Views: 835

Answers (2)

BENY
BENY

Reputation: 323236

When you have series , I think astype('timedelta64[s]') can do what you need

pd.Series(t1-t2).astype('timedelta64[s]')/3600
0   -138.403611
dtype: float64

Upvotes: 1

niraj
niraj

Reputation: 18208

It's missing days, I think you need total_seconds():

print(pd.Timedelta(t2 - t1).total_seconds()/3600)

From documentation:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 **6) / 10 **6

computed with true division enabled.

Upvotes: 3

Related Questions