Fix Python – Add column with number of days between dates in DataFrame pandas


Asked By – Jase Villam

I want to subtract dates in ‘A’ from dates in ‘B’ and add a new column with the difference.

          A        B
one 2014-01-01  2014-02-28 
two 2014-02-03  2014-03-01

I’ve tried the following, but get an error when I try to include this in a for loop…

import datetime
mdate1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
delta =  (mdate1 - rdate1).days
print delta

What should I do?

Now we will see solution for issue: Add column with number of days between dates in DataFrame pandas


Assuming these were datetime columns (if they’re not apply to_datetime) you can just subtract them:

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

In [11]: df.dtypes  # if already datetime64 you don't need to use to_datetime
A    datetime64[ns]
B    datetime64[ns]
dtype: object

In [12]: df['A'] - df['B']
one   -58 days
two   -26 days
dtype: timedelta64[ns]

In [13]: df['C'] = df['A'] - df['B']

In [14]: df
             A          B        C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days

Note: ensure you’re using a new of pandas (e.g. 0.13.1), this may not work in older versions.

This question is answered By – Andy Hayden

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0