Python 为什么pd.Timedelta模int有效,但不加int?

Python 为什么pd.Timedelta模int有效,但不加int?,python,pandas,Python,Pandas,可以对任意数量的时间增量使用模,但加法会导致不支持的错误。下面的例子 import pandas as pd pd.to_timedelta(7, "s") % 3 pd.to_timedelta(7, "s") + 3 导致 TypeError Traceback (most recent call last) <ipython-input-2-edd04d4a1971> in <module>

可以对任意数量的时间增量使用模,但加法会导致不支持的错误。下面的例子

import pandas as pd
pd.to_timedelta(7, "s") % 3
pd.to_timedelta(7, "s") + 3
导致

TypeError                                 Traceback (most recent call last)
<ipython-input-2-edd04d4a1971> in <module>
      3 pd.to_timedelta(7, "s") % 3
      4 
----> 5 pd.to_timedelta(7, "s") + 3

TypeError: unsupported operand type(s) for +: 'Timedelta' and 'int'
TypeError回溯(最近一次调用)
在里面
3 pd.至_timedelta(7,“s”)%3
4.
---->5 pd.至_timedelta(7,“s”)+3
TypeError:不支持+:'Timedelta'和'int'的操作数类型

这有更深层次的原因吗?

只有在显示要使用的日期时间的哪一部分时,才能这样做, 例如:

time=pd.to_timedelta(7, "s")
print(time)
0 days 00:00:07
print(time.seconds%3)
1
您不能使用不同的类型进行划分查看,我们可以看到,
\uuuuumod\uuuuu
函数只调用
\uuuuuu divmod\uuu
函数,并返回第二个值;如下所示:

def __divmod__(self, other):
    # Naive implementation, room for optimization
    div = self // other
    return div, self - div * other

因此,
%
将处理任何可以分割
时间增量
对象的东西-我们可以在同一链接中看到
\uuuu\uu\rDiv\uuuuu>从实现中接受的东西。

感谢您的挖掘。如果我的解释正确,Pandas将假定
int
为ns(请参阅)。除此之外,我觉得这与错误不一致…确切地说-如果您查看
\uuuu add\uuuu
方法,它只会尝试使用lambda进行添加,而不会将int转换为
datetime
对象。可能会在github上打开一个问题-即使它被拒绝,您也可能会弄清楚为什么会出现这种行为。关于这个打开(和关闭)的问题和PRs,原因似乎是int//timedelta以某种方式进入了文档中,作为计算Linux时代的一种方式,所以清除这种行为会破坏一切。至少对于某些类似的操作,它们现在会发出警告(请参阅)。