首页 > 解决方案 > 获取特定月份中某个日期范围内的天数

问题描述

一直没能找到这个问题的答案。基本上我想要做的是:

取一个日期范围,例如 10 月 10 日到 11 月 25 日。确定日期范围中有多少天在 10 月和有多少在 11 月的最佳算法是什么。

像这样的东西:

def daysInMonthFromDaterange(daterange, month):
    # do stuff
    return days

我知道这很容易实现,我只是想知道是否有一个非常好的或有效的算法。

谢谢

标签: pythonalgorithm

解决方案


从这个答案中借用算法如何在 Python 中将日期范围划分为月份? ,这可能有效。输入是date格式的,但如果愿意,可以更改为日期字符串:

import datetime
begin = '2018-10-10'
end = '2018-11-25'

dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
    #print(today)
    tomorrow = today + one_day
    if tomorrow.month != today.month:
        start_dates.append(tomorrow)
        end_dates.append(today)
    today = tomorrow

end_dates.append(dt_end)

out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
    diff = (end - start).days
    print('{} to {}: {} days'.format(start.strftime(out_fmt), end.strftime(out_fmt), diff))

结果:

10 October 2018 to 31 October 2018: 21 days
01 November 2018 to 25 November 2018: 24 days

推荐阅读