2

I'm trying to calculate the difference between two datetime columns (dtype = datetime64[ns]) in pandas. I can successfully calculate the delta in hours, but I want the result to be days.

Example

foo_df = pd.DataFrame({'date_1': ['2019-08-07 09:25:07'], 
                       'date_2': ['2019-08-08 01:01:00']}).astype('datetime64[ns]')

foo_df['delta'] =  foo_df['date_2'] - foo_df['date_1']

result

    date_1              date_2              delta
0   2019-08-07 09:25:07 2019-08-08 01:01:00 15:35:53

Desired Result

    date_1              date_2              delta
0   2019-08-07 09:25:07 2019-08-08 01:01:00 1

NOTE: The delta should be 1 because date_2 is the next day. I only need to calculate if the day is different. I can do this if I convert the date columns to strings, but ideally, I'd like to avoid that since this should be possible to do with dtype; datetime64[ns]

3
  • 1
    are you looking for (foo_df['date_2'].dt.date - foo_df['date_1'].dt.date).dt.days ? Commented Jan 21, 2020 at 2:45
  • 2
    dt.days() should work, since you are interested in that part of the datetime Commented Jan 21, 2020 at 2:45
  • Bingo! that was exactly what I was looking for! Commented Jan 21, 2020 at 2:50

1 Answer 1

1

Subtract the dates, then get the number of days from the Timedelta:

foo_df['delta'] = (foo_df.date_2.dt.date - foo_df.date_1.dt.date).dt.days

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.