0

I have multiple columns with datetime format "14-09-2021 12:00:00 AM". I have converted them to date with the below code.

df['Column1'] = pd.to_datetime(df['Column1']).dt.date
df['Column2'] = pd.to_datetime(df['Column2']).dt.date

Intention is to take the difference between the two columns to identify the difference in days. When I take the difference df['diff']=df['Column1']-df['Column2'] I get the result as say "- 39 days" and not jus "- 39" (Image added below for clarity)

enter image description here

Intention is to get the difference in integer or number format (i.e just 39 and not 39 days), I'm not sure on how to go about this or when I have erred in the above code.

Help would be much appreciated.

7
  • 1
    Like the accepted answer recommends you can grab just the days through the dt accessor -> df['diff'] = (df['Column1'] - df['Column2']).dt.days Commented Dec 16, 2021 at 3:50
  • You could add Series.abs to get the absolute value if needing all positive numbersdf['diff'] = (df['Column1'] - df['Column2']).dt.days.abs() Commented Dec 16, 2021 at 3:51
  • @HenryEcker I tried the above code but got an error TypeError: bad operand type for abs(): 'datetime.date' Commented Dec 16, 2021 at 3:56
  • It works fine pandas 1.3.5. (I used this DataFrame df = pd.DataFrame({'Column1': ['2021-01-09', '2021-01-09'], 'Column2': ['2022-08-31', '2022-01-09']}) to start with and ran your conversion code to change the dtype of each column) What version are you using? Commented Dec 16, 2021 at 4:00
  • 1
    @HenryEcker df['diff']=df['diff'].dt.days did the trick, thank you for providing the above references. Commented Dec 16, 2021 at 4:47

1 Answer 1

0

Try this df['diff'] = df['diff'].astype(int)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.