在使用Pandas包的时候,遇到时间加减出现的报错

'datetime.date’是datetime的一种时间格式;
‘Timestamp’(注意是大写的字母)是Pandas的一种时间格式。
这两个虽然都是都表示时间,但是直接相加减,会报错unsupported operand type(s) for -: ‘datetime.date’ and ‘Timestamp’。

同时,也应该注意到,如果是’datetime.datetime’与Pandas的’Timestamp’相加减,就不会报错。

错误复现

下面我们使用一个简单的代码,使这个错误复现:

dt.date.today() - (pd.Timestamp(dt.date.today()))

上面结果就会出现以下结果
TypeError: unsupported operand type(s) for -: 'datetime.date' and 'Timestamp'

解决方法

1.将'datetime.date'转换成pandas的'Timestamp'
使用pd.Timestamp(dt.date.today())就可以完成

2.将’datetime.date’转换成’datetime.datetime’也可以完成

import datetime as dt
today_d = dt.date.today()
today_dt = dt.datetime.combine(today,dt.time())

可以参照python中date和datetime互转总结

例如:

dt.datetime.now() - (pd.Timestamp(dt.datetime.now()))

运行结果为Timedelta('0 days 00:00:00'),这样也就解决了这个问题。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐