Skip to content
Advertisement

subtracting time intervals from column dates in dataframes Pandas Python

How would I be able to subtract 1 second and 1 minute and 1 month from data['date'] column?

import pandas as pd 

d = {'col1': [4, 5, 2, 2, 3, 5, 1, 1, 6], 'col2': [6, 2, 1, 7, 3, 5, 3, 3, 9], 
     'label':['Old','Old','Old','Old','Old','Old','Old','Old','Old'],
     'date': ['2022-01-24 10:07:02', '2022-01-27 01:55:03', '2022-01-30 19:09:03', '2022-02-02 14:34:06',
              '2022-02-08 12:37:03', '2022-02-10 03:07:02', '2022-02-10 14:02:03', '2022-02-11 00:32:25',
              '2022-02-12 21:42:03']}

data = pd.DataFrame(d)

# subtract the dates by 1 second  
date_mod_s = pd.to_datetime(data['date'])
# subtract the dates by 1 minute
date_mod_m = pd.to_datetime(data['date'])
# subtract the dates by 1 month
date_mod_M = pd.to_datetime(data['date'])

Advertisement

Answer

Your date column is of type string. Convert it to pd.Timestamp and you can use pd.DateOffset:

pd.to_datetime(data["date"]) - pd.DateOffset(months=1, minutes=1, seconds=1)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement