Skip to content Skip to sidebar Skip to footer

How Can I Use Pandas.date_range() To Obtain A Time Series With N Specified Periods (equal) Between A Specified Start And End Date

I'd like to get a list or series of n dates between a start and end date (inclusive of those bounds), but dateIndex=pd.date_range(start=dt.datetime.today().date(), end=pd.to_dateti

Solution 1:

I don't think you can do this just with date_range, but why not use numpy's linspace:

In [11]: start = pd.Timestamp('2012-01-01')

In [12]: end = pd.Timestamp('2012-02-01')

In [13]: np.linspace(start.value, end.value, 10)  # 10 dates inclusive
Out[13]:
array([  1.32537600e+18,   1.32567360e+18,   1.32597120e+18,
         1.32626880e+18,   1.32656640e+18,   1.32686400e+18,
         1.32716160e+18,   1.32745920e+18,   1.32775680e+18,
         1.32805440e+18])

In [14]: pd.to_datetime(np.linspace(start.value, end.value, 10))
Out[14]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-0100:00:00, ..., 2012-02-0100:00:00]
Length: 10, Freq: None, Timezone: None

You could pass this as a freq, but this may/will be inaccurate for times which don't evenly divide:

In [21]: (end - start)/ 9
Out[21]: datetime.timedelta(3, 38400)

In [22]: ((end - start)/ 9).total_seconds()
Out[22]: 297600.0# Note: perhaps there's a better way to pass this as a freq?
In [23]: pd.date_range(start=start, end=end, freq='%iS' % ((end - start)/ 9).total_seconds())
Out[23]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-0100:00:00, ..., 2012-02-0100:00:00]
Length:10, Freq: 297600S, Timezone: None

Solution 2:

As of Pandas 0.23 (or earlier), you can just use pandas.date_range like you originally tried. It does not raise an error and behaves as you would expect. Example:

pd.date_range('2016-01-01', '2017-01-01', periods=13, tz='utc')
Out[44]: 
DatetimeIndex(['2016-01-01 00:00:00+00:00', '2016-01-31 12:00:00+00:00',
               '2016-03-02 00:00:00+00:00', '2016-04-01 12:00:00+00:00',
               '2016-05-02 00:00:00+00:00', '2016-06-01 12:00:00+00:00',
               '2016-07-02 00:00:00+00:00', '2016-08-01 12:00:00+00:00',
               '2016-09-01 00:00:00+00:00', '2016-10-01 12:00:00+00:00',
               '2016-11-01 00:00:00+00:00', '2016-12-01 12:00:00+00:00',
               '2017-01-01 00:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)

There were 366 days in 2016 (a leap year), so time stamps are 30.5 days apart.

Post a Comment for "How Can I Use Pandas.date_range() To Obtain A Time Series With N Specified Periods (equal) Between A Specified Start And End Date"