繁体   English   中英

如何在 Python 中的开始日期和结束日期之间的所有日子进行迭代

[英]How to iterate on all days between start and end date in 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 循环,但是就将它们嵌入上述函数而言,我真的不知道该怎么做。

先感谢您。

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)

如果您想运行一个创建日、月和年的循环,那么您必须注意一些事项! 1-闰年。 (二月加一天) 2 个月的天数不一样。 3-您必须使其可维护!

所以这是我的解决方案:

def leap_year(this_year):
    if (this_year % 4) == 0:
        if (this_year % 100) == 0:
            if (this_year % 400) == 0:
                return True

    return False


for my_year in range(2020, 2100 + 1):
    print(my_year)
    year_months = {
        1: 31,
        2: 29 if leap_year(my_year) else 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31,
    }
    for my_month in year_months.keys():
        day = year_months[my_month]
        for my_day in range(1, day + 1):
            print("year = {0}, month: {1}, day: {2}".format(my_year, my_month, my_day))

!!! +1 in range(2020, 2100 + 1) 之所以存在,是因为 range() 函数总是计算范围的下限。 希望你过得愉快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM