首页 > 解决方案 > 如何在Python中迭代开始日期和结束日期之间的所有日子

问题描述

使用 Python,我从一个需要日、月和年输入的函数调用。

客观的

我正在提取从 10 月到 4 月运行的篮球数据,因此每天都有大量数据。我希望能够遍历从 2013 年 10 月 1 日到 2020 年 8 月 1 日的每一天/每一月和每一年。

client.team_box_scores(
    day=, month=2, year=2017, 
    output_type=OutputType.CSV, 
    output_file_path="./1_1_2017_box_scores.csv"
)

初步研究

通过研究,我发现了datetime模块以及我可以利用的for 循环,但是就将它们嵌入到上述函数中而言,我真的不知道该怎么做。

先感谢您。

标签: pythonloopsdatetime

解决方案


import datetime

start_date = datetime.date(year=2013, month=10, day=1)
end_date   = datetime.date(year=2020, month=8,  day=1)

current_date = start_date
# Iterating over all dates from start date until end date including end date ("inclusive")
while current_date <= end_date:
    # Calling the function that you need, with the appropriate day-month-year combination
    # Outputting to path that is build based on current day-month-year combination
    client.team_box_scores(
        day=current_date.day, month=current_date.month, year=current_date.year,
        output_type=OutputType.CSV,
        output_file_path=f"./{current_date.day}_{current_date.month}_{current_date.year}_box_scores.csv"
    )
    # Advancing current date by one day
    current_date += datetime.timedelta(days=1)


推荐阅读