Search⌘ K
AI Features

Manipulating Dates by Adding Time Intervals

Explore how to manipulate dates by adding or subtracting time intervals with Pandas DateOffset and Timedelta functions. Understand different units and methods to adjust date and time data efficiently.

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 DataFrame
staff = pd.read_csv("staff.csv")
# change the date type
staff = staff.astype({
"date_of_birth": "datetime64[ns]",
"start_date": "datetime64[ns]"
})
# create raise_date column
staff["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 ...