【问题标题】:TypeError: 'str' object cannot be interpreted as an integer python for loopTypeError:'str'对象不能解释为整数python for循环
【发布时间】:2020-04-21 20:28:06
【问题描述】:

我正在尝试创建一个函数,该函数返回从给定年份和给定月份到今天的年份和月份的数据。为简单起见,我用外循环和内循环的打印语句替换了我希望我的函数执行的操作。我收到错误 TypeError: 'str' 对象不能被解释为整数

定义函数

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.............

调用功能

frequency_database(df,1,2015)

错误

TypeError: 'str' 对象不能被解释为整数

根据要求进行堆栈跟踪

---------------------------------------------------------------------------
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

【问题讨论】:

  • today_year=int(today.strftime('%Y'))替换today_year=today.strftime('%Y')
  • 请包含您的异常的堆栈跟踪并告诉我们它指示的是哪一行

标签: python loops datetime for-loop


【解决方案1】:

问题是你试图给range 一个str 这是today_year=today.strftime('%Y')

只要换行

today_year=today.strftime('%Y')

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

正如Stargazer 所指出的,您可以这样做,

today_year = today.year

而不是将str 转换为int

【讨论】:

  • 没必要。只需 today.year 将年份返回为 int
  • 当然。我将用它来更新答案。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-06-19
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多