Iterating through a range of dates in Python

后端 未结 23 1598
醉酒成梦
醉酒成梦 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 05:02

    Can't* believe this question has existed for 9 years without anyone suggesting a simple recursive function:

    from datetime import datetime, timedelta
    
    def walk_days(start_date, end_date):
        if start_date <= end_date:
            print(start_date.strftime("%Y-%m-%d"))
            next_date = start_date + timedelta(days=1)
            walk_days(next_date, end_date)
    
    #demo
    start_date = datetime(2009, 5, 30)
    end_date   = datetime(2009, 6, 9)
    
    walk_days(start_date, end_date)
    

    Output:

    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
    

    Edit: *Now I can believe it -- see Does Python optimize tail recursion? . Thank you Tim.

提交回复
热议问题