【问题标题】:Looping dates dynamically inside a function with Python使用 Python 在函数内动态循环日期
【发布时间】:2016-12-06 23:44:19
【问题描述】:

我正在调用 API,但该 API 一次只能为我提供一年的数据。但我想使用一个循环来提取超过一年的数据。

我在一个范围内有以下开始和结束日期:

startdate = datetime.date(2011, 9, 6)
enddate = datetime.date(2014, 10, 12)

我编写了一个很长的函数(此处未显示)并使用以下代码调用该函数并传入参数:

get_hourly_WSI_latlong_historical (startdate, enddate, lat, long, fields = None)

如何在循环函数中编写下面的大段代码? ...它必须是函数格式。在下面的代码中,我希望根据我的“startdate”和“enddate”变量动态地导出这些值,而不是明确列出每个开始和结束日期上面提供。 我该怎么做?

WSI_Hourly = get_hourly_WSI_latlong_historical (datetime.date(2011, 9, 6), datetime.date(2011, 12, 31), 39.742721,-105.0816042, fields=None)
WSI_Hourly1 = get_hourly_WSI_latlong_historical (datetime.date(2012,1,1), datetime.date(2012,12,31), 39.742721,-105.0816042, fields=None)
WSI_Hourly = WSI_Hourly.append(WSI_Hourly1,ignore_index=True)
WSI_Hourly1 = get_hourly_WSI_latlong_historical (datetime.date(2013,1,1), datetime.date(2013,12,31), 39.742721,-105.0816042, fields=None)
WSI_Hourly = WSI_Hourly.append(WSI_Hourly1,ignore_index=True)
WSI_Hourly1 = get_hourly_WSI_latlong_historical (datetime.date(2014,1,1), datetime.date(2014,10,12), 39.742721,-105.0816042, fields=None)
WSI_Hourly = WSI_Hourly.append(WSI_Hourly1,ignore_index=True)

非常感谢任何帮助。

【问题讨论】:

    标签: python function api loops date


    【解决方案1】:

    只需查找开始日期和结束日期之间的年份

    from datetime import datetime
    
    def get_hourly_WSI_latlong_historical(datetime1, datetime2):
        #YOUR CODE HERE
    
    def my_wrapper_func(startdate, enddate):
        middle_years = range(startdate.year+1, enddate.year)
        _all = []
        _all.append(get_hourly_WSI_latlong_historical(startdate, datetime(startdate.year, 12, 31)))
        for year in middle_years:
            _all.append(get_hourly_WSI_latlong_historical(datetime(year, 1, 1), datetime(year, 12, 31)))
        _all.append(get_hourly_WSI_latlong_historical(datetime(enddate.year, 1, 1), datetime(enddate.year, 12, 31)))
        return _all
    
    my_wrapper_func(datetime(2010, 2, 1), datetime(2015, 2,1))
    

    【讨论】:

    • 感谢您的快速响应。我收到以下错误:invalid syntax for : 'for year in middle_years:' 错误指针胡萝卜指向该代码行的 ':' 部分...想法?
    • 当我运行上面的代码时,我得到以下错误:“ TypeError: get_hourly_WSI_latlong_historical() missing 2 required positional arguments: 'lat' and 'long' " ;我尝试自己放置 lat long 参数,但它出错了......我不确定我是否把它们放在正确的地方......想法?
    • 按照您在函数中定义的顺序放置它们应该不会出错,您可能需要再次检查您的函数定义
    • 当我运行我的函数并运行它成功执行的以下代码时......所以我认为我的函数很好:WSI_Hourly = get_hourly_WSI_latlong_historical (datetime.date(2015,1,1), datetime. date(2015,2,1), 41.0340, 73.7629, fields = None) ...想法?
    • my_wrapper_func 中,您还必须将参数列表中的参数分配为get_hourly_WSI_latlong_historical 中的定义。上面的代码只是向您展示了如何循环您想要的日期时间的示例,它与您的函数无关。只需将函数替换为您的函数并添加所需的参数,它应该可以正常工作。如果没有,请使用您的代码更新您的帖子,以便我可以调试您的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 2018-07-06
    • 2017-01-18
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多