AttributeError: 'Timedelta' object has no attribute 'dt'

Viewed 12230

I have a df:

    id  timestamp                       data  group Date
27001   27242   2020-01-01 09:07:21.277 19.5    1   2020-01-01
27002   27243   2020-01-01 09:07:21.377 19.0    1   2020-01-01
27581   27822   2020-01-02 07:53:05.173 19.5    1   2020-01-02
27582   27823   2020-01-02 07:53:05.273 20.0    1   2020-01-02
27647   27888   2020-01-02 10:01:46.380 20.5    1   2020-01-02
...

and I would like to calculate the time difference between row 1 and row 2 in seconds. I could do it with

df['timediff'] = (df['timestamp'].shift(-1) - df['timestamp']).dt.total_seconds()

However, when I zoom in to look at only 2 rows, ie. row1 and row0, with code:

difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).dt.total_seconds()

it returned error

AttributeError: 'Timedelta' object has no attribute 'dt'

Why is this happening?

3 Answers

By inspection the following is a Series:

type(df['timestamp'].shift(-1) - df['timestamp'])

Series has an accessor (dt) object for datetime like properties. However, the following is a TimeDelta with no dt accessor:

type(df.loc[0, 'timestamp'] - df.loc[1, 'timestamp'])

Just call the following (without the dt accessor) to solve the error:

difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()

In case you end up here and want to extract days: (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).days

As @hpaulj said in the comments, dt is only associated with dataframe like object.

So to obtain total seconds you have to use difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()

Related