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
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.
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.
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.
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
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