-3

I have a pandas dataframe in python with two dates, stored as strings in the following format

Date 1         Date 2
2020-06-02     2021-09-17
2020-07-11     2022-03-22
2020-08-04     2021-06-17

What I am looking to do is return a data frame that has these two columns, as well as a third column that has the number of days between those two dates like such:

Date 1         Date 2         Days Inbetween
2020-06-02     2021-09-17     472
2020-07-11     2022-03-22     619
2020-08-04     2021-06-17     317

Is there a function or way to automatically do this calculation?

Thanks

Ryan Reid
  • 189
  • 1
  • 3
  • 9
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). We expect you to do your basic research before posting a question. The `datetime` package gives you plenty of tools: simply subtract the two dates. – Prune Aug 17 '20 at 18:15
  • I hate to be that person that downvotes a question, but I've done it here. I think that it's fine to ask questions, and there are no dumb questions, but you did not even Google this. – Sam Creamer Aug 17 '20 at 18:19
  • 1
    Possible duplicate: [How to calculate number of days between two given dates](https://stackoverflow.com/q/151199/984421). – ekhumoro Aug 17 '20 at 18:29
  • @SamCreamer, the downvote button here is not for "dumb questions". Everybody has a dumb question once in a while. Downvotes are meant for when the question "does not show research effort, is unclear, or not useful". Posts that ask questions that could be answered by a simple google search fall under "no research effort", and should rightly be downvoted and closed without an answer so as not to encourage more of the same. – Pranav Hosangadi Aug 17 '20 at 18:55

2 Answers2

2

See if this helps:

df['days Inbetween'] = (pd.to_datetime(df['Date 2'])-pd.to_datetime(df['Date 1']))/np.timedelta64(1,'D')

OR:

df['days Inbetween'] = pd.to_datetime(df['Date 2'])-pd.to_datetime(df['Date 1'])
Subasri sridhar
  • 809
  • 5
  • 13
1

1> You can find the No of Days between two date range using the below code

from datetime import date

f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)

2> Then you can iterate the same code with the date range you have by converting them from string to date format first and get the array of days using the above code inside a loop

3> Finally You can add the Days column to the existing pandas DF as below:-

Using DataFrame.insert() to add a column

df.insert(2, "Days", days_array , True)

Best of luck :)