Python中特定年份的时差
Posted
技术标签:
【中文标题】Python中特定年份的时差【英文标题】:Time difference in specific year in Python 【发布时间】:2022-01-23 12:11:35 【问题描述】:我有一个这样的时间范围:
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
【问题讨论】:
这很棘手,因为这取决于您认为“月数”是多少。你总是只有一个月的第一天吗?在这种情况下,.year * 12
和 .month
(在 date
对象上)会有所帮助。 EV。处理.day
的差异(例如,
你能解释一下你的输出吗?
【参考方案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
检查结果:
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
【讨论】:
【参考方案2】:您可以通过 timedelta 的.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
【讨论】:
以上是关于Python中特定年份的时差的主要内容,如果未能解决你的问题,请参考以下文章