Search code examples
pythonpandastimestampdate-rangedatetimeindex

How to change one of the Timestamp in pandas date range?


I want to change all of March into April.

date = pd.date_range("2008-01-01", "2021-03-31", freq = "QS-MAR")     
date

I try to change them by using timedelta.

It can run, but the data do not change.

for time in date:
    print(type(time))
    if time.month == 3:
        time += datetime.timedelta(31)
date

DatetimeIndex(['2008-03-01', '2008-06-01', '2008-09-01', '2008-12-01',
               '2009-03-01', '2009-06-01', '2009-09-01', '2009-12-01',
               '2010-03-01', '2010-06-01', '2010-09-01', '2010-12-01',
               '2011-03-01', '2011-06-01', '2011-09-01', '2011-12-01',
               '2012-03-01', '2012-06-01', '2012-09-01', '2012-12-01',
               '2013-03-01', '2013-06-01', '2013-09-01', '2013-12-01',
               '2014-03-01', '2014-06-01', '2014-09-01', '2014-12-01',
               '2015-03-01', '2015-06-01', '2015-09-01', '2015-12-01',
               '2016-03-01', '2016-06-01', '2016-09-01', '2016-12-01',
               '2017-03-01', '2017-06-01', '2017-09-01', '2017-12-01',
               '2018-03-01', '2018-06-01', '2018-09-01', '2018-12-01',
               '2019-03-01', '2019-06-01', '2019-09-01', '2019-12-01',
               '2020-03-01', '2020-06-01', '2020-09-01', '2020-12-01',
               '2021-03-01'],
              dtype='datetime64[ns]', freq='QS-MAR')

Is it possible to achieve? Thanks.


Solution

  • Use pd.Series instead so you can assign directly:

    s = pd.Series(pd.date_range("2008-01-01", "2021-03-31", freq = "QS-MAR"))
    
    s.loc[s.dt.month==3] += pd.offsets.DateOffset(months=1)
    
    print (s)
    
    0    2008-04-01
    1    2008-06-01
    2    2008-09-01
    3    2008-12-01
    4    2009-04-01
    5    2009-06-01
    ...
    48   2020-04-01
    49   2020-06-01
    50   2020-09-01
    51   2020-12-01
    52   2021-04-01
    dtype: datetime64[ns]