Iterating through a range of dates in Python

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

    Use the dateutil library:

    from datetime import date
    from dateutil.rrule import rrule, DAILY
    
    a = date(2009, 5, 30)
    b = date(2009, 6, 9)
    
    for dt in rrule(DAILY, dtstart=a, until=b):
        print dt.strftime("%Y-%m-%d")
    

    This python library has many more advanced features, some very useful, like relative deltas—and is implemented as a single file (module) that's easily included into a project.

提交回复
热议问题