Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a year from a datetime column in pandas

I have a datetime column as below -

>>> df['ACC_DATE'].head(2) 538   2006-04-07 550   2006-04-12 Name: ACC_DATE, dtype: datetime64[ns] 

Now, I want to subtract an year from each row of this column. How can I achieve the same & which library can I use?

The expected field -

        ACC_DATE    NEW_DATE 538   2006-04-07  2005-04-07 549   2006-04-12  2005-04-12 
like image 488
0nir Avatar asked Jul 01 '15 19:07

0nir


People also ask

How do I subtract time columns in pandas?

We create a Panda DataFrame with 3 columns. Then we set the values of the to and fr columns to Pandas timestamps. Next, we subtract the values from df.fr by df.to and convert the type to timedelta64 with astype and assign that to df.

Can you subtract dates in pandas?

The timedelta function allows you to perform date addition and date subtraction calculations that can add or subtract specified numbers of days from a date and return a new date before or after the original date.

How do you subtract a year in Python?

The easiest way to subtract years from a date in Python is to use the dateutil extension. The relativedelta object from the dateutil. relativedelta module allows you to subtract any number of years from a date object.


1 Answers

You can use DateOffset to achieve this:

In[88]: df['NEW_DATE'] = df['ACC_DATE'] - pd.DateOffset(years=1) df  Out[88]:          ACC_DATE   NEW_DATE index                       538   2006-04-07 2005-04-07 550   2006-04-12 2005-04-12 
like image 58
EdChum Avatar answered Sep 22 '22 21:09

EdChum