简体   繁体   English

获取特定月份在日期范围内的天数

[英]Get number of days in a specific month that are in a date range

Haven't been able to find an answer to this problem.一直无法找到这个问题的答案。 Basically what I'm trying to do is this:基本上我想做的是这样的:

Take a daterange, for example October 10th to November 25th.取一个日期范围,例如 10 月 10 日到 11 月 25 日。 What is the best algorithm for determining how many of the days in the daterange are in October and how many are in November.确定日期范围中有多少天在 10 月以及有多少天在 11 月的最佳算法是什么。

Something like this:像这样的东西:

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

I know that this is pretty easy to implement, I'm just wondering if there's a very good or efficient algorithm.我知道这很容易实现,我只是想知道是否有一个非常好的或有效的算法。

Thanks谢谢

Borrowing the algorithm from this answer How do I divide a date range into months in Python?从这个答案中借用算法如何在 Python 中将日期范围划分为月份? , this might work. ,这可能会奏效。 The inputs are in date format, but can be changed to date strings if preferred:输入采用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))

result:结果:

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

The problem as stated may not have a unique answer.所述问题可能没有唯一的答案。 For example what should you get from daysInMonthFromDaterange('Feb 15 - Mar 15', 'February') ?例如,你应该从daysInMonthFromDaterange('Feb 15 - Mar 15', 'February')什么? That will depend on the year!那要看年份了!

But if you substitute actual days, I would suggest converting from dates to integer days, using the first of the month to the first of the next month as your definition of a month.但是,如果您替换实际天数,我建议将日期转换为整数天数,使用一个月的第一天到下个月的第一天作为您对月份的定义。 This is now reduced to intersecting intervals of integers, which is much easier.这现在被简化为整数的相交间隔,这要容易得多。

The assumption that the first of the month always happened deals with months of different lengths, variable length months, and even correctly handles the traditional placement of the switch from the Julian calendar to the Gregorian.每月的第一天总是发生的假设处理不同长度的月份、可变长度的月份,甚至正确处理从儒略历转换为公历的传统位置。 See cal 1752 for that.参见cal 1752 (It will not handle that switch for all locations though. Should you be dealing with a library that does Romanian dates in 1919, you could have a problem...) (虽然它不会处理所有位置的切换。如果你正在处理一个在 1919 年处理罗马尼亚日期的图书馆,你可能会遇到问题......)

You can use the datetime module:您可以使用 datetime 模块:

from datetime import datetime

start = datetime(2018,10,10)
end = datetime(2018,11,25)
print((end - start).days)

Something like this would work:像这样的事情会起作用:

def daysInMonthFromDaterange(date1, date2, month):
    return [x for x in range(date1.toordinal(), date2.toordinal()) if datetime.date.fromordinal(x).year == month.year and datetime.date.fromordinal(x).month == month.month]

print(len(days_in_month(date(2018,10,10), date(2018,11,25), date(2018,10,01))))

This just loops through all the days between date1 and date2, and returns it as part of a list if it matches the year and month of the third argument.这只是循环遍历 date1 和 date2 之间的所有日子,如果它与第三个参数的年和月匹配,则将其作为列表的一部分返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM