Pandas: Subtracting two date columns and the result being an integer

Learn, how to subtract two date columns and the result being an integer in Python pandas?
Submitted by Pranit Sharma, on February 12, 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.

Problem statement

Suppose that we are given a pandas dataframe containing some datetime columns, we need to subtract one column from another and the result is the difference in the numbers of days as an integer.

Subtracting two date columns and the result being an integer

For this purpose, we will access the values for both columns and subtract each of these values and use dt.days() attribute of datetime to represent the integer values as the difference between the dates.

Let us understand with the help of an example,

Python program to subtract two date columns and the result being an integer

# Import pandas
import pandas as pd

# Import numpy
import numpy as np

# Import datetime
import datetime

# Creating a dataframe
df = pd.DataFrame({
    'A': ['12/07/2001','13/07/2002','14/07/2003'], 
    'B': ['13/08/2002','14/08/2003','15/08/2004']
})

# Display original dataframe
print("Original DataFrame:\n",df,"\n")

# Converting columns of df into datetime
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

# Subtracting one column from another
df['res'] = (df['B'] - df['A']).dt.days

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: Pandas: Subtracting two date columns and the result being an integer

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.