Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_datetime(expiry).date(), periods=n)

results with ValueError: Must specify two of start, end, or periods. I cannot use freq=Freq argument because my date range won't be uniform - it may be anywhere from a month to 2 years span, thus I'd like an equally spaced time series with n points.

Thanks!

like image 460
arosner09 Avatar asked Dec 14 '22 20:12

arosner09


2 Answers

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-01 00:00:00, ..., 2012-02-01 00: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-01 00:00:00, ..., 2012-02-01 00:00:00]
Length: 10, Freq: 297600S, Timezone: None
like image 79
Andy Hayden Avatar answered Dec 28 '22 08:12

Andy Hayden


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.

like image 26
Joooeey Avatar answered Dec 28 '22 06:12

Joooeey