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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With