你可以通过
.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