如何在 Pandas 数据框中减去两个日期时间值

How can I subtract two date time values in a Pandas Dataframe

我正在做一个项目,我需要减去两个日期时间值以获得天数。数据示例如下所示:


                   ALARM_DATE               CONT_DATE  \
0      2020/06/18 00:00:00+00  2020/06/23 00:00:00+00   
1      2020/06/01 00:00:00+00  2020/06/04 00:00:00+00   
2      2020/08/10 00:00:00+00  2020/03/01 00:00:00+00   
3      2020/03/31 00:00:00+00  2020/04/01 00:00:00+00   
4      2020/04/14 00:00:00+00  2020/04/19 00:00:00+00   
...                       ...                     ...   

我试过简单地减去这些值,但显然那没有用。有人可以帮忙吗?

首先将您的列转换为实际日期:

df['ALARM_DATE'] = pd.to_datetime(df['ALARM_DATE'])
df['CONT_DATE'] = pd.to_datetime(df['CONT_DATE'])

或者:

df[['ALARM_DATE', 'CONT_DATE']] = df[['ALARM_DATE', 'CONT_DATE']].apply(pd.to_datetime)

输出:

>>> df['CONT_DATE'] - df['ALARM_DATE']
0      5 days
1      3 days
2   -162 days
3      1 days
4      5 days
dtype: timedelta64[ns]