pandas :从 pandas 表中的日期减去当前日期 [英] pandas: subtracting current date from the date in a pandas table

查看:111
本文介绍了 pandas :从 pandas 表中的日期减去当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算今天和由历史数据组成的熊猫数据之间的天数差.下面是预期的代码:

I am attempting to calculate the difference in days between todays and a pandas data consisting of historical data. Below is the intended code:

df['diff'] = pd.to_datetime( df['date']) - pd.datetime.now().date()

但是,它会产生以下错误:

However, it produces the following error:

TypeError:-:"DatetimeIndex"和以下不受支持的操作数类型 'datetime.date'

TypeError: unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date'

pandas表中的日期列如下所示:

The date column in the pandas table looks like this:

0       2018-12-18
1       2018-12-18
2       2018-12-18
3       2018-12-18
4       2018-12-18

如何解决此错误.预先感谢.

How do I fix this error. Thanks in advance.

推荐答案

您必须减去相同的类型- datetimes datetime (零次)或日期日期.

You have to subtract same types - datetimes with datetime (with zero times) or dates with date.

Timestamp.now 一起使用 Timestamp.normalize Timestamp.floor 来删除time:

Use Timestamp.now with Timestamp.normalize or Timestamp.floor for remove times:

df['diff'] = pd.to_datetime( df['date']) - pd.Timestamp.now().normalize() 

df['diff'] = pd.to_datetime( df['date']) - pd.Timestamp.now().floor('d')

您还可以使用 replace :

You can also use replace:

dt = pd.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
df['diff'] = pd.to_datetime( df['date']) - dt

或将Datetimes转换为 date 用于减去相同类型:

Or convert Datetimes to dates for subtract same types:

dt = datetime.datetime.now().date()
df['diff'] = pd.to_datetime(df['date']).dt.date - dt

示例:

rng = pd.date_range('2018-04-03', periods=10, freq='100D')
df = pd.DataFrame({'date': rng}) 

df['diff'] = pd.to_datetime( df['date']) - pd.Timestamp.now().normalize() 
print (df)
        date      diff
0 2018-04-03 -261 days
1 2018-07-12 -161 days
2 2018-10-20  -61 days
3 2019-01-28   39 days
4 2019-05-08  139 days
5 2019-08-16  239 days
6 2019-11-24  339 days
7 2020-03-03  439 days
8 2020-06-11  539 days
9 2020-09-19  639 days

这篇关于 pandas :从 pandas 表中的日期减去当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆