0

My function should return data starting from a given year and given month to today's year and month. 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...
        for x in range(start_month,13):
            print('Inner loop enter for month number',x)
            # Some function...

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
2
  • Replace today_year=today.strftime('%Y') with today_year=int(today.strftime('%Y')) Commented Jan 3, 2020 at 9:14
  • Please include the stack trace of your exception and tell us which line it is indicating Commented Jan 3, 2020 at 9:14

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

No need to that. Just today.year will return the year as an int

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.