I want to subtract dates in 'A' from dates in 'B' and add a new column with the difference.
df
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
date1=df['A'][0]
date2=df['B'][0]
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?
Assuming these were datetime columns (if they're not apply
to_datetime
) you can just subtract them:Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.
A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:
If your columns aren't in datetime format. The shorter syntax would be:
df.A = pd.to_datetime(df.A)
How about this:
To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html
So,
Which returns