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

前端 未结 6 1476
长情又很酷
长情又很酷 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:32

    Using Datetimeindex and Periods from Pandas, together with dictionary comprehension:

    import pandas as pd
    
    begin = '20100101'
    end = '20101231'
    
    start = dt.datetime.strptime(begin, '%Y%m%d')
    finish = dt.datetime.strptime(end, '%Y%m%d')
    
    dates = pd.DatetimeIndex(start=start, end=finish, freq='D').tolist()
    quarters = [d.to_period('Q') for d in dates]
    df = pd.DataFrame([quarters, dates], index=['Quarter', 'Date']).T
    
    quarterly_dates = {str(q): [ts.strftime('%Y%m%d') 
                                for ts in df[df.Quarter == q].Date.values.tolist()]
                               for q in quarters}
    
    >>> quarterly_dates
    {'2010Q1': ['20100101',
      '20100102',
      '20100103',
      '20100104',
      '20100105',
    ...
      '20101227',
      '20101228',
      '20101229',
      '20101230',
      '20101231']}
    
    >>> quarterly_dates.keys()
    ['2010Q1', '2010Q2', '2010Q3', '2010Q4']
    

提交回复
热议问题