Addition/subtraction 的整数和带时间戳的整数数组不再受支持。代替 adding/subtracting `n`,使用 `n * obj.freq`

Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting `n`, use `n * obj.freq`

我正在使用 pytrends 库提取 google 趋势,但出现以下错误:

Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq

timeframes = []
datelist = pd.date_range('2004-01-01', '2018-01-01', freq="AS")
date = datelist[0]
while date <= datelist[len(datelist)-1]:
    start_date = date.strftime("%Y-%m-%d")
    end_date = (date+4).strftime("%Y-%m-%d")
    timeframes.append(start_date+' '+end_date)
    date = date+3

您不能像 date+4 那样对日期和数字求和,因为谁知道这是哪个单位,4h4d、...?


您可以使用 datetime.timedelta,这里是一个示例,如果您的意思是 days

from datetime import timedelta

end_date = (date + timedelta(days=4)).strftime("%Y-%m-%d")
# ...
date = date + timedelta(days=3)

既然您已经在使用 Pandas,为什么还要导入其他东西呢?你可以这样做:

import pandas as pd                                            # your code
date = pd.date_range('2004-01-01', '2018-01-01', freq="AS")    # your code

freq = 'D'                                                     # 'H' for hours, etc.
date = date + pd.Timedelta(3, unit=freq)                       # Perform the action
print(date)

输出(与azro的回答相同):

DatetimeIndex(['2004-01-04', '2005-01-04', '2006-01-04', '2007-01-04',
               '2008-01-04', '2009-01-04', '2010-01-04', '2011-01-04',
               '2012-01-04', '2013-01-04', '2014-01-04', '2015-01-04',
               '2016-01-04', '2017-01-04', '2018-01-04'],
              dtype='datetime64[ns]', freq=None)

使用这种方法的另一个原因是,您会发现自己处于这样一种情况:您正在向日期动态添加内容,例如在方法内部,并且您将单位作为参数传递。

如果您使用的是 timedelta(days=3),您将无法更改任何其他内容(小时、分钟等),但只能更改天数!