Home »
Python »
Python Programs
Subtract a year from a datetime column in pandas
Given a pandas dataframe, we have to Subtract a year from a datetime column.
By Pranit Sharma Last updated : October 01, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually, the date is present in the format of "yy-mm-dd", and the time is present in the format of "HH:MM:SS".
Problem statement
Suppose we are having a DataFrame with a column containing a date, we will create a new column in which we will insert a date by subtracting one year from its adjacent column value.
Subtracting a year from a datetime column
For this purpose, first convert column values from string to datetime time by using the to_datetime() method and then subtract a year (pd.DateOffset(years=1)) from the datetime column and assign the result to the new column. Consider the below-given code statements,
df['Date'] = pd.to_datetime(df['Date'])
df['New Date'] = df['Date']-pd.DateOffset(years=1)
Let us understand with the help of an example,
Python program to subtract a year from a datetime column in pandas
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {'Date':['2001-12-07','2002-11-06','2003-10-05','2004-09-04','2005-08-03']}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")
# Converting date value from string to datetime value
df['Date'] = pd.to_datetime(df['Date'])
# Subtracting a year from old date
df['New Date'] = df['Date']-pd.DateOffset(years=1)
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »
Advertisement
Advertisement