2
votes

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]

1
are you looking for (foo_df['date_2'].dt.date - foo_df['date_1'].dt.date).dt.days ? - anky
dt.days() should work, since you are interested in that part of the datetime - sammywemmy
Bingo! that was exactly what I was looking for! - FunnyChef

1 Answers

1
votes

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