Manipulating Dates by Adding Time Intervals
Learn how to add to and subtract from a date with Python Pandas.
We'll cover the following...
We'll cover the following...
The DateOffset function
One Pandas function we can use to add or subtract dates and times is DateOffset. It can be used with both dates and times. We only need to specify the unit and quantity to be added or subtracted. Consider a case where we want to give a raise to our employees one year after they’re hired. In the staff, we can create a column called raise_date by adding one year to the start_date column.
Python 3.8
import pandas as pd# create the DataFramestaff = pd.read_csv("staff.csv")# change the date typestaff = staff.astype({"date_of_birth": "datetime64[ns]","start_date": "datetime64[ns]"})# create raise_date columnstaff["raise_date"] = staff["start_date"] + pd.DateOffset(years=1)print(staff[["start_date","raise_date"]].head())
The DateOffset function is quite simple. We only need to adjust the unit and quantity. For instance, the following line of code adds six months to the ...