Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, 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
like image 690
Bushra Akram Avatar asked Apr 11 '20 07:04

Bushra Akram


2 Answers

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!

like image 101
gsamaras Avatar answered Sep 24 '22 02:09

gsamaras


You can't sum a date and a number like date+4 because who knows which unit this is, 4h, 4d, ... ?


You may use datetime.timedelta, here's an example if you meant days

from datetime import timedelta

end_date = (date + timedelta(days=4)).strftime("%Y-%m-%d")
# ...
date = date + timedelta(days=3)
like image 26
azro Avatar answered Sep 23 '22 02:09

azro