Iterating through a range of dates in Python

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

    I have a similar problem, but I need to iterate monthly instead of daily.

    This is my solution

    import calendar
    from datetime import datetime, timedelta
    
    def days_in_month(dt):
        return calendar.monthrange(dt.year, dt.month)[1]
    
    def monthly_range(dt_start, dt_end):
        forward = dt_end >= dt_start
        finish = False
        dt = dt_start
    
        while not finish:
            yield dt.date()
            if forward:
                days = days_in_month(dt)
                dt = dt + timedelta(days=days)            
                finish = dt > dt_end
            else:
                _tmp_dt = dt.replace(day=1) - timedelta(days=1)
                dt = (_tmp_dt.replace(day=dt.day))
                finish = dt < dt_end
    

    Example #1

    date_start = datetime(2016, 6, 1)
    date_end = datetime(2017, 1, 1)
    
    for p in monthly_range(date_start, date_end):
        print(p)
    

    Output

    2016-06-01
    2016-07-01
    2016-08-01
    2016-09-01
    2016-10-01
    2016-11-01
    2016-12-01
    2017-01-01
    

    Example #2

    date_start = datetime(2017, 1, 1)
    date_end = datetime(2016, 6, 1)
    
    for p in monthly_range(date_start, date_end):
        print(p)
    

    Output

    2017-01-01
    2016-12-01
    2016-11-01
    2016-10-01
    2016-09-01
    2016-08-01
    2016-07-01
    2016-06-01
    

提交回复
热议问题