I would like to mention a date (say, 2016-10-27) and a duration (say, 5 days) and I want a date range 5 days into the past, beginning from the oldest day.
Example: 2016-10-22 2016-10-23 2016-10-24 2016-10-25 2016-10-26
I have tried this
pd.date_range('2016-10-27', freq='D', periods=5)[::-1]
But this is giving me wrong and reverse order.
DatetimeIndex(['2016-10-31', '2016-10-30', '2016-10-29', '2016-10-28',
'2016-10-27'],
dtype='datetime64[ns]', freq='-1D')
How can I do it>
IIUC we can use end parameter:
In [240]: pd.date_range(end='2016-10-27', freq='D', periods=5)
Out[240]: DatetimeIndex(['2016-10-23', '2016-10-24', '2016-10-25', '2016-10-26', '2016-10-27'], dtype='datetime64[ns]', freq='D')
or:
In [242]: pd.date_range(end='2016-10-27', freq='D', periods=5) - pd.Timedelta('1 day')
Out[242]: DatetimeIndex(['2016-10-22', '2016-10-23', '2016-10-24', '2016-10-25', '2016-10-26'], dtype='datetime64[ns]', freq='D')
Option 1
Offset your start date
pd.date_range(
start=pd.Timestamp('2016-10-27') - pd.offsets.Day(4),
freq='D', periods=5)
DatetimeIndex(['2016-10-23', '2016-10-24', '2016-10-25', '2016-10-26',
'2016-10-27'],
dtype='datetime64[ns]', freq='D')
Option 2
Obnoxious!!!! Just terrible. My only justification for posting this is that I wanted to find some alternative.
pd.to_datetime(['2016-10-27']).values + pd.to_timedelta([1], 'D')[:, None] * -np.arange(5)[::-1]
array([['2016-10-23T00:00:00.000000000', '2016-10-24T00:00:00.000000000',
'2016-10-25T00:00:00.000000000', '2016-10-26T00:00:00.000000000',
'2016-10-27T00:00:00.000000000']], dtype='datetime64[ns]')
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