Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a date range backwards using pandas?

Tags:

python

pandas

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>

like image 779
maximusdooku Avatar asked Nov 15 '25 19:11

maximusdooku


2 Answers

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')
like image 138
MaxU - stop WAR against UA Avatar answered Nov 18 '25 09:11

MaxU - stop WAR against UA


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]')
like image 35
piRSquared Avatar answered Nov 18 '25 09:11

piRSquared