且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中迭代一系列日期

更新时间:2023-08-17 18:01:46

为什么有两个嵌套迭代?对于我来说,它只产生一个相同的数据列表:

Why are there two nested iterations? For me it produces the same list of data with only one iteration:

for single_date in (start_date + timedelta(n) for n in range(day_count)):
    print ...

没有列表被存储,只有一个生成器被迭代。此外,生成器中的if似乎是不必要的。

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

毕竟,线性序列只需要一个迭代器,而不是两个。

After all, a linear sequence should only require one iterator, not two.

也许最优雅的解决方案是使用生成器函数来完全隐藏/抽象范围的日期:

Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

from datetime import timedelta, date

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
    print single_date.strftime("%Y-%m-%d")

注意:为了与内置 range()的一致性()这个迭代在到 end_date 之前停止的功能。所以对于包容性迭代,使用第二天,就像你在 range()中一样。

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().