Related Articles

Related Articles

Addition and Subtraction on TimeDelta objects using Pandas – Python
  • Last Updated : 29 Aug, 2020

TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. 

Operations on TimeDelta dataframe or series – 

1) Addition – 

df['Result'] = df['TimeDelta1'] + df['TimeDelta2']

2) Subtraction – 

df['Result'] = df['TimeDelta1'] - df['TimeDelta2']

Return: Return the dataframe after operations is performed.



Example #1 :

In this example, we can see that by using various operations on date and time, we are able to get the addition and subtraction on the dataframe having TimeDelta object values.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import pandas and numpy
import pandas as pd
import numpy as np
  
# Perform addition operation
a = pd.Series(pd.date_range('2020-8-10', periods=5, freq='D'))
b = pd.Series([pd.Timedelta(days=i) for i in range(5)])
  
gfg = pd.DataFrame({'A': a, 'B': b})
gfg['Result'] = gfg['A'] + gfg['B']
  
print(gfg)

chevron_right


Output :

            A             B        Result

0 2020-08-10 0 days 2020-08-10

1 2020-08-11 1 days 2020-08-12

2 2020-08-12 2 days 2020-08-14



3 2020-08-13 3 days 2020-08-16

4 2020-08-14 4 days 2020-08-18

Example #2 :

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import pandas and numpy
import pandas as pd
import numpy as np
  
# Perform addition operation
a = pd.Series(pd.date_range('2020-8-10', periods=4, freq='D'))
b = pd.Series([pd.Timedelta(days=i) for i in range(4)])
  
gfg = pd.DataFrame({'A': a, 'B': b})
gfg['Result'] = gfg['A'] - gfg['B']
  
print(gfg)

chevron_right


Output :

           A             B        Result

0 2020-08-10 0 days 2020-08-10

1 2020-08-11 1 days 2020-08-10

2 2020-08-12 2 days 2020-08-10

3 2020-08-13 3 days 2020-08-10

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :