【问题标题】:what to fix to solve the TypeError: an integer is required (got type str) [duplicate]解决TypeError的解决方法:需要一个整数(获取类型str)[重复]
【发布时间】:2018-04-19 20:10:25
【问题描述】:

我对计算年份的选择有疑问。

python flux2nc.py ../data/output/fluxes/ ../data/output/
    IMPORTANT: ../data/output/fluxes/ SHOULD CONTAIN ONLY FLUXES FILES!!!
    Choose output parameter
    1 - Precipitation
    2 - Evapotranspiration
    3 - Runoff
    4 - Base flow
    5 - Snow Water Equivalent
    6 - Soil moisture
    Choose output (1 a 6)>3
    Enter start year:2011
    End year:2012
    Traceback (most recent call last):
      File "flux2nc.py", line 240, in <module>
        main()
      File "flux2nc.py", line 234, in main
        flux2nc(sys.argv[1],sys.argv[2])
      File "flux2nc.py", line 120, in flux2nc
        inidate = dt.date(start_year,1,1)
    TypeError: an integer is required (got type str)

我知道这个问题已经提出,但由于我对 python 的了解有限,我找不到确切的解决方案,而且脚本非常复杂。

这里是源代码的一部分,与我的问题有关。

# import dependencies
import sys
import os, string
# handle dates...
import datetime as dt
# NetCDF and Numeric
from netCDF4 import *
from numpy import *

    # if the date information is not set get it from user
    if start_year == None:
        # for what date?
        start_year = input("Enter start year:")
    if end_year == None:
        end_year = input("End year:")

    # set date information in datetime object
    inidate = dt.date(start_year,1,1)
    enddate = dt.date(end_year,12,31)

    # calculate number of days in time series
    days = enddate.toordinal() - inidate.toordinal()+1

【问题讨论】:

  • 您好!由于您在这里似乎是新人,请查看how to askon-topic。这将帮助其他人帮助你。如果您有任何疑问,请以Minimal, Complete, and Verifiable example 的形式提供您的代码。编码愉快!
  • 请注意错误提示“需要一个整数(获取类型 str)”。当您通过input() 获得用户输入时,您会得到一个字符串。 dt.date 需要整数(请参阅documentation,因此您必须转换输入。这个问题可能会有所帮助:How can I read inputs as integers

标签: python python-3.x python-2.7


【解决方案1】:

您的错误可能是您忘记将input(...) 转换为int

start_year = input('Enter start year')
start_year = int(start_year)

您应该对 end_yearoutput 执行相同的操作。

注意:如果没有源代码,很难尝试帮助您。我需要推断出很多东西来帮助你诊断这个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多