当我尝试这个时:
>>> a = numpy.datetime64('1995-12-31')
>>> b = a + pandas.Timedelta(1, unit='M')
>>> print(b)
我期待看到
1996-01-31
但我得到
1996-01-30 10:29:06.
知道为什么吗?非常感谢。
最佳答案
正如@hpaulj 在他的回答中已经提到的:
There's an inherent ambiguity in adding a 'month' to a time, since months vary in length.
此外,在版本
0.25.0
, Pandas dropped support供单位使用M
(月)和 Y
(年)在 Timedelta
职能。但正如官方 Pandas 中所述guide , 你应该使用 时间增量 绝对持续时间和 日期偏移对于尊重日历算术的相对持续时间,这正是我们在您的情况下所需要的:
The basic DateOffset acts similar to
dateutil.relativedelta
(relativedelta documentation) that shifts a date time by the corresponding calendar duration specified.
因此,使用您的示例:
In [7]: a = numpy.datetime64('1995-12-31')
: b = pandas.Timestamp(a) + pandas.DateOffset(months=1)
: b
Out[7]: Timestamp('1996-01-31 00:00:00')
注意:您可以随时使用
to_numpy
方法,如果需要转换pandas.Timestamp
至 numpy.datetime64
.
关于python - 使用 timedelta 将一个月添加到 datetime64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54794431/