Iterating through a range of dates in Python

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

    import datetime
    
    def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
      # inclusive=False to behave like range by default
      if step.days > 0:
        while start < stop:
          yield start
          start = start + step
          # not +=! don't modify object passed in if it's mutable
          # since this function is not restricted to
          # only types from datetime module
      elif step.days < 0:
        while start > stop:
          yield start
          start = start + step
      if inclusive and start == stop:
        yield start
    
    # ...
    
    for date in daterange(start_date, end_date, inclusive=True):
      print strftime("%Y-%m-%d", date.timetuple())
    

    This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count and most importantly the code becomes easier to read as you call the function from multiple places.

提交回复
热议问题