Iterating through a range of dates in Python

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

    What about the following for doing a range incremented by days:

    for d in map( lambda x: startDate+datetime.timedelta(days=x), xrange( (stopDate-startDate).days ) ):
      # Do stuff here
    
    • startDate and stopDate are datetime.date objects

    For a generic version:

    for d in map( lambda x: startTime+x*stepTime, xrange( (stopTime-startTime).total_seconds() / stepTime.total_seconds() ) ):
      # Do stuff here
    
    • startTime and stopTime are datetime.date or datetime.datetime object (both should be the same type)
    • stepTime is a timedelta object

    Note that .total_seconds() is only supported after python 2.7 If you are stuck with an earlier version you can write your own function:

    def total_seconds( td ):
      return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
    

提交回复
热议问题