Py学习  »  Python

Python中特定年份的时差

Jume • 3 年前 • 1377 次点击  

我有这样一个时间范围:

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

如何计算当前年的月数?

例如:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129678
 
1377 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Enrique Benito Casado
Reply   •   1 楼
Enrique Benito Casado    3 年前
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

检查结果:

print(calculate_differentmonths(runtime_start, runtime_end, current_year)) 

结果12

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

结果5

Patrick Artner
Reply   •   2 楼
Patrick Artner    3 年前

你可以通过 .days 关于时间差:

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)

输出:

12 vs expected:  12
5 vs expected:  5