1

I have two dates: 2005/04/10 and 2018/02/11.

The following code calculates the difference in terms of years, months and days:

from datetime import datetime
from dateutil.relativedelta import relativedelta
start_date = datetime(2005,4,10)
end_date = datetime(2018,2,11)
difference = relativedelta(end_date, start_date)
print(difference.years)
print(difference.months)
print(difference.days)

The output is:

12
10
1

12 years, 10 months and 1 day. The problem is that I am not interested in months I only want it in years and days. In my example, it should be 12 years and 306 days. I know that a good approximation is 10 months*30=300 days but the result is 301, not 306. I want to calculate precisely the days taking into account leap months and the difference in a number of days for each month. Is there any built-in method in Python to do that?

Look I already did my research on StackOverflow to find an answer but all the one related to my question do not answer to my problem.

Salvatore D'angelo
  • 1,019
  • 3
  • 14
  • 39

2 Answers2

4

After the code you already wrote, do this:

mid_date = datetime(start_date.year + difference.years, start_date.month, start_date.day)
print((end_date - mid_date).days)

That gives 307 for your example input.

The idea is to offset the original start_date by difference.years to avoid double-counting that portion of the difference.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • This is a good idea but it is not 100% perfect. I think leap years could shift the result of one or more days as in your case. – Salvatore D'angelo Jun 30 '18 at 17:24
  • @SalvatoreD'angelo: I think the disagreement between your answer of 306 for this case and my answer of 307 is a semantic one. That is, you haven't clearly defined the rules for this. – John Zwinck Jul 01 '18 at 01:52
1

Thanks to John's comment I wrote this code that I think satisfies my request:

from datetime import datetime
from dateutil.relativedelta import relativedelta

start_date = datetime(2005,4,10)
end_date = datetime(2018,2,11)      
difference = relativedelta(end_date, start_date)

remaining_days = 0
if  start_date != datetime(start_date.year, 1, 1):
    end_first_year = datetime(start_date.year, 12, 31)
    remaining_days += (end_first_year - start_date).days
if  end_date != datetime(start_date.year, 1, 1):
    begin_last_year = datetime(end_date.year, 1, 1)
    remaining_days += (end_date - begin_last_year).days
print(difference.years)
print(remaining_days)

This gives exactly 306 remaining days. Can anyone suggest a less verbose snippet of code?

Salvatore D'angelo
  • 1,019
  • 3
  • 14
  • 39