Iterating through a range of dates in Python

后端 未结 23 1355
醉酒成梦
醉酒成梦 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
    
    0 讨论(0)
  • 2020-11-22 05:08

    For completeness, Pandas also has a period_range function for timestamps that are out of bounds:

    import pandas as pd
    
    pd.period_range(start='1/1/1626', end='1/08/1627', freq='D')
    
    0 讨论(0)
  • 2020-11-22 05:09

    This is the most human-readable solution I can think of.

    import datetime
    
    def daterange(start, end, step=datetime.timedelta(1)):
        curr = start
        while curr < end:
            yield curr
            curr += step
    
    0 讨论(0)
  • 2020-11-22 05:10

    Using pendulum.period:

    import pendulum
    
    start = pendulum.from_format('2020-05-01', 'YYYY-MM-DD', formatter='alternative')
    end = pendulum.from_format('2020-05-02', 'YYYY-MM-DD', formatter='alternative')
    
    period = pendulum.period(start, end)
    
    for dt in period:
        print(dt.to_date_string())
    
    0 讨论(0)
  • 2020-11-22 05:11
    import datetime
    from dateutil.rrule import DAILY,rrule
    
    date=datetime.datetime(2019,1,10)
    
    date1=datetime.datetime(2019,2,2)
    
    for i in rrule(DAILY , dtstart=date,until=date1):
         print(i.strftime('%Y%b%d'),sep='\n')
    

    OUTPUT:

    2019Jan10
    2019Jan11
    2019Jan12
    2019Jan13
    2019Jan14
    2019Jan15
    2019Jan16
    2019Jan17
    2019Jan18
    2019Jan19
    2019Jan20
    2019Jan21
    2019Jan22
    2019Jan23
    2019Jan24
    2019Jan25
    2019Jan26
    2019Jan27
    2019Jan28
    2019Jan29
    2019Jan30
    2019Jan31
    2019Feb01
    2019Feb02
    
    0 讨论(0)
提交回复
热议问题