问题
I am using pytrends library to extract google trends and i am getting the following error:
Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting
n
, usen * 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
回答1:
You may not sum a date and a number like date+4
because who knows which unit this is, 4h
, 4d
, 4m
, ... ?
You may use datetime.timedelta, here's an example if you meant days
end_date = (date+timedelta(days=4)).strftime("%Y-%m-%d")
# ...
date = date+timedelta(days=3)
回答2:
Since you already use Pandas, why bothering importing other stuff? You can do:
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)
Output (same as azro's answer):
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)
Another reason for using this approach is that you can find yourself in a situation where you are adding dynamically stuff to a date, inside a method for example, and you are passing the unit as a parameter.
If you were using timedelta(days=3)
, you wouldn't be able to change anything else (hours, minutes, etc.) but days!
来源:https://stackoverflow.com/questions/61153546/addition-subtraction-of-integers-and-integer-arrays-with-timestamp-is-no-longer