如何在 pandas 中减去两个日期(类型:日期时间)?

how to substract two dates (type: datetime) in pandas?

我将此列命名为:temps 在数据框中命名为:df

0      2022-03-18 14:50:11
1      2022-03-18 14:50:00
2      2022-03-18 14:49:59
3      2022-03-18 14:48:00
4      2022-03-18 14:40:00

关于我的数据框 df 的信息

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 172 entries, 0 to 171
Data columns (total 5 columns):
 #   Column       Non-Null Count  Dtype         
---  ------       --------------  -----         
 0   temps        172 non-null    datetime64[ns]
 1   id           172 non-null    int64         

我需要减去每两个成功的行并在几秒钟内得到结果

我该怎么做?

使用.view(int)将日期转换为数字,.div(1e9)将结果纳秒转换为秒,.diff()计算每个连续行之间的差异:

df['temps'] = df['temps'].view(int).div(1e9).diff().fillna(0)

输出:

>>> df
   temps
0    0.0
1  -11.0
2   -1.0
3 -119.0
4 -480.0