-1

I have a time range like this:

runtime_start = datetime.date(2021,1,1)
runtime_end = datetime.date(2022,3,1)
current_year = datetime.date.today().year

How can I calculate the number of month in the current_year?

Some Examples:

runtime_start = 2021,1,1 | runtime_end = 2022,3,1 | current_year = 2021 | output = 12
runtime_start = 2021,1,1 | runtime_end = 2021,6,1 | current_year = 2021 | output= 5
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Jume
  • 63
  • 5
  • It is tricky, because it depends on what do you consider "number of month". Do you have always only the first day of a month? In such case `.year * 12` and `.month` (on `date` object) will help. Ev. handle differences of `.day` (e.g. < 15 days: one month less, 15 days more: one month more) – Giacomo Catenazzi Dec 22 '21 at 09:25
  • Can you explain little your outputs? – Hemant Sah Dec 22 '21 at 09:37

2 Answers2

1
import datetime

runtime_start = datetime.date(2021,1,1)
runtime_end = datetime.date(2022,3,1)
current_year = datetime.date.today().year


def calculate_differentmonths(runtime_start, runtime_end, current_year):
     if current_year == runtime_end.year:
         run_months = runtime_end.month - runtime_start.month 
     else:    
         years_month = (current_year - runtime_start.year) * 12
         run_months =  datetime.date.today().month + years_month

     return run_months

check the results:

print(calculate_differentmonths(runtime_start, runtime_end, current_year)) 

result 12

print(calculate_differentmonths(datetime.date(2021,1,1), datetime.date(2021,6,1), current_year))

result 5

Enrique Benito Casado
  • 1,914
  • 1
  • 20
  • 40
0

You can estimate the amount of months by the .days of a timedelta:

import datetime

current_year = datetime.date.today().year
start_of_curr = datetime.date(current_year,1,1)
end_of_curr = datetime.date(current_year,12,31)

data = [(datetime.date(2021,1,1), datetime.date(2022,3,1),  12), 
        (datetime.date(2021,1,1), datetime.date(2021,6,1),  5)]

for runtime_start, runtime_end, months in data:

    # limit the used start/end dates
    frm = start_of_curr  if runtime_start < start_of_curr else runtime_start
    to = runtime_end if runtime_end <= end_of_curr else end_of_curr

    print(int(round((to-frm).days / ((end_of_curr-start_of_curr).days/12),0)), 
        "vs expected: ", months)

Output:

12 vs expected:  12
5 vs expected:  5
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69