Home > Back-end >  Time difference in specific year in Python
Time difference in specific year in Python

Time:12-23

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

CodePudding user response:

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

CodePudding user response:

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
  • Related