Iterating through a range of dates in Python

后端 未结 23 1737
醉酒成梦
醉酒成梦 2020-11-22 04:40

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 ge

23条回答
  •  我寻月下人不归
    2020-11-22 04:57

    Slightly different approach to reversible steps by storing range args in a tuple.

    def date_range(start, stop, step=1, inclusive=False):
        day_count = (stop - start).days
        if inclusive:
            day_count += 1
    
        if step > 0:
            range_args = (0, day_count, step)
        elif step < 0:
            range_args = (day_count - 1, -1, step)
        else:
            raise ValueError("date_range(): step arg must be non-zero")
    
        for i in range(*range_args):
            yield start + timedelta(days=i)
    

提交回复
热议问题