Given a date range how can we break it up into N contiguous sub-intervals?

前端 未结 6 1485
长情又很酷
长情又很酷 2020-12-15 21:18

I am accessing some data through an API where I need to provide the date range for my request, ex. start=\'20100101\', end=\'20150415\'. I thought I would speed this up by

6条回答
  •  忘掉有多难
    2020-12-15 21:41

    I would actually follow a different approach and rely on timedelta and date addition to determine the non-overlapping ranges

    Implementation

    def date_range(start, end, intv):
        from datetime import datetime
        start = datetime.strptime(start,"%Y%m%d")
        end = datetime.strptime(end,"%Y%m%d")
        diff = (end  - start ) / intv
        for i in range(intv):
            yield (start + diff * i).strftime("%Y%m%d")
        yield end.strftime("%Y%m%d")
    

    Execution

    >>> begin = '20150101'
    >>> end = '20150228'
    >>> list(date_range(begin, end, 4))
    ['20150101', '20150115', '20150130', '20150213', '20150228']
    

提交回复
热议问题