python迭代_在Python中迭代一系列日期

I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.

day_count = (end_date - start_date).days + 1

for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:

print strftime("%Y-%m-%d", single_date.timetuple())

Notes

I'm not actually using this to print. That's just for demo purposes.

The start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report).

Sample Output

For a start date of 2009-05-30 and an end date of 2009-06-09:

2009-05-30

2009-05-31

2009-06-01

2009-06-02

2009-06-03

2009-06-04

2009-06-05

2009-06-06

2009-06-07

2009-06-08

2009-06-09

解决方案

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 ...

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.

Update after discussion with John Machin:

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")

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().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值