Iterating through a range of dates in Python

后端 未结 23 1641
醉酒成梦
醉酒成梦 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:46

    import datetime
    
    def daterange(start, stop, step_days=1):
        current = start
        step = datetime.timedelta(step_days)
        if step_days > 0:
            while current < stop:
                yield current
                current += step
        elif step_days < 0:
            while current > stop:
                yield current
                current += step
        else:
            raise ValueError("daterange() step_days argument must not be zero")
    
    if __name__ == "__main__":
        from pprint import pprint as pp
        lo = datetime.date(2008, 12, 27)
        hi = datetime.date(2009, 1, 5)
        pp(list(daterange(lo, hi)))
        pp(list(daterange(hi, lo, -1)))
        pp(list(daterange(lo, hi, 7)))
        pp(list(daterange(hi, lo, -7))) 
        assert not list(daterange(lo, hi, -1))
        assert not list(daterange(hi, lo))
        assert not list(daterange(lo, hi, -7))
        assert not list(daterange(hi, lo, 7)) 
    

提交回复
热议问题