Search code examples
pythonpython-3.xpandasdatetimepython-datetime

Increment attributes of a datetime Series in pandas


I have a Series containing datetime64[ns] elements called series, and would like to increment the months. I thought the following would work fine, but it doesn't:

    series.dt.month += 1

The error is

    ValueError: modifications to a property of a datetimelike object are not supported. Change values on the original.

Is there a simple way to achieve this without needing to redefine things?


Solution

  • First, I created timeseries date example:

    import datetime
    t = [datetime.datetime(2015,4,18,23,33,58),datetime.datetime(2015,4,19,14,32,8),datetime.datetime(2015,4,20,18,42,44),datetime.datetime(2015,4,20,21,41,19)]
    import pandas as pd
    df = pd.DataFrame(t,columns=['Date'])
    

    Timeseries:

    df
    Out[]: 
                     Date
    0 2015-04-18 23:33:58
    1 2015-04-19 14:32:08
    2 2015-04-20 18:42:44
    3 2015-04-20 21:41:19
    

    Now increment part, you can use offset option.

    df['Date']+pd.DateOffset(days=30)
    

    Output:

    df['Date']+pd.DateOffset(days=30)
    Out[66]: 
    0   2015-05-18 23:33:58
    1   2015-05-19 14:32:08
    2   2015-05-20 18:42:44
    3   2015-05-20 21:41:19
    Name: Date, dtype: datetime64[ns]