Subtract a year from a datetime column in pandas

Given a pandas dataframe, we have to Subtract a year from a datetime column.
Submitted by Pranit Sharma, on September 20, 2022

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.

Subtracting a year from a datetime column

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

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.

Let us understand with the help of an example,

Python code 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:

Example: Subtract a year from a datetime column

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.