How can I use pandas.date_range () to get a time series with n specified periods (equal) between the specified start and end date

I would like to get a list or a series of n dates between the start and end dates (including these boundaries), but

dateIndex=pd.date_range(start=dt.datetime.today().date(), end=pd.to_datetime(expiry).date(), periods=n) 

Results with ValueError: must indicate two beginnings, an end, or periods. I cannot use the argument freq = Freq, because my date range will not be uniform - it can be from a month to two years, so I would like to have the same time intervals with n points.

Thanks!

+3
python pandas datetime time-series
source share
1 answer

I don't think you can only do this with date_range , but why not use numpy 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 can pass this as a frequency, but it may / will not be accurate for times that are not shared evenly:

 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 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 
+6
source share

All Articles