0
votes

I am trying to create a function that returns data starting from a given year and given month to today's year and month. For simplicity I have replaced what I want my function to do with print statements of outer loop and inner loop. I am getting error TypeError: 'str' object cannot be interpreted as an integer

Defining function

def frequency_database(df,start_month,start_year):
    data = pd.DataFrame([])
    import datetime
    start_month=int(start_month)
    start_year=int(start_year)
    today = datetime.date.today()
    today_year=today.strftime('%Y')

    for y in range(start_year,today_year):
        print('Outer loop enter for year', y)
        Some function here which I want to do.............
        for x in range(start_month,13):
            print('Inner loop enter for month number',x)
            Some function here which I want to do.............

Calling funtion

frequency_database(df,1,2015)

Error

TypeError: 'str' object cannot be interpreted as an integer

Stack Trace as requested

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-06567ae5d027> in <module>
     12             print('Inner loop enter for month number',x)
     13 
---> 14 frequency_database(df,1,2015)

<ipython-input-37-06567ae5d027> in frequency_database(df, start_month, start_year)
      7     today_year=today.strftime('%Y')
      8 
----> 9     for y in range(start_year,today_year):
     10         print('Outer loop enter for year', y)
     11         for x in range(start_month,13):

TypeError: 'str' object cannot be interpreted as an integer
1
Replace today_year=today.strftime('%Y') with today_year=int(today.strftime('%Y')) - han solo
Please include the stack trace of your exception and tell us which line it is indicating - khelwood

1 Answers

5
votes

The problem is you tried to give range a str which is today_year=today.strftime('%Y').

Just replace the line

today_year=today.strftime('%Y')

with

today_year=int(today.strftime('%Y'))

As pointed out by Stargazer, you could do,

today_year = today.year

instead of converting the str to int