0

I have a dataframe:

   date1          date2
2021-11-02    2021-11-02
2021-11-02    2021-11-03
2021-11-02    2021-11-07

I want to add column "day" which is equal to difference between date2 and date1. I do df["day"] = df["date2"] - df["date1"] But brings error TypeError: unsupported operand type(s) for -: 'str' and 'str' How to fix it? How to turn them into timestamp?

skulldoger
  • 145
  • 7
  • I did not understand your question correctly. But if the only problem is that the strings can not be subtracted, convert them to integers. – H.sojoodi Nov 17 '21 at 19:04

1 Answers1

0
df['day'] = (df['date2'].astype('datetime64') - df['date1'].
             astype('datetime64')).dt.days
print(df)
        date1       date2  day
0  2021-11-02  2021-11-02    0
1  2021-11-02  2021-11-03    1
2  2021-11-02  2021-11-07    5
Алексей Р
  • 7,507
  • 2
  • 7
  • 18