如何获取 Python 中两个日期之间特定月份的天数

How to get the number of Days in a Specific Month between Two Dates in Python

我有两个日期字段 campaign_start_datecampaign_end_date。我想计算 campaign_start_datecampaign_end_date 之间每个月的天数。

例如:

campaign_start_date  = September 7 2017
campaign_end_date    = November 6 2017

解决方案应该是:

Total No:of days       = 61 days
No: of months          = 3 months
Month 1                = 9/7/2017 to 9/30/2017
Month 2                = 10/1/2017 to 10/31/2017
Month 3                = 11/1/2017 to 11/6/2017
No:of days in Month 1  = 24 days
No:of days in Month 2  = 31 days
No:of days in Month 3  = 6 days

如何使用 Python 实现此目的? 到目前为止我已经取得了:

@api.multi
    def print_date(self):
        start_date = datetime.strptime(self.start_date, "%Y-%m-%d %H:%M:%S")
        end_date = datetime.strptime(self.end_date, "%Y-%m-%d %H:%M:%S")
        campaign_start_date = date(start_date.year,start_date.month,start_date.day)
        campaign_end_date = date(end_date.year,end_date.month,end_date.day)
        duration = (campaign_end_date-campaign_start_date).days  
        return True

计算持续时间(以天为单位):

from datetime import date

campaign_start_date = date(2017, 9, 7)
campaign_end_date = date(2017, 10, 6)
duration = (campaign_end_date-campaign_start_date).days
print campaign_start_date, campaign_end_date, duration 

进一步计算的一些提示:

import calendar

campaign_end_month_start = campaign_end_date.replace(day=1)
days_in_month_campaign_end = (campaign_end_date - campaign_end_month_start).days + 1

range_startmonth = calendar.monthrange(campaign_start_date.year, campaign_start_date.month)
campaign_start_month_ends = campaign_start_date.replace(day=range_startmonth[1])

days_in_month_campaign_begins = (campaign_start_month_ends - campaign_start_date).days

这样您就可以计算广告系列每个月的天数(请注意检查 campaign_end_date 是否在 campaign_start_date

以外的月份

对于计算,您还可以访问日期字段,例如

campaign_start_date.day
campaign_start_date.month
campaign_start_date.year

要计算广告系列中涉及的月份数并获取月份列表以计算每月的持续时间,您可以使用此功能(基于 中 m.antkowicz 的回答).在循环之前和内部将日期设置为 1 (current = current.replace(day=1)) 很重要,否则当您的开始日期是一个月的 31 日并且下个月短于 31 天或者您有更长的时间时,您将跳过一个月:

from datetime import date, datetime, timedelta    
current = campaign_start_date
result = [current]

current = current.replace(day=1)
while current <= campaign_end_date:
    current += timedelta(days=32)
    current = current.replace(day=1)
    result.append(datetime(current.year, current.month, 1))

print result, len(result)

打印(当您使用 current.strftime('%Y-%m-%d'):

['2017-09-07', '2017-10-01', '2017-11-01'] 3

现在您可以遍历结果列表并计算每个月的天数:

durations= []
for curr in result:
    curr_range = calendar.monthrange(curr.year, curr.month)
    curr_duration = (curr_range[1] - curr.day)+1
    if (curr.month < campaign_end_date.month):
        durations.append(curr_duration)
    else:
        durations.append(campaign_end_date.day)

print durations

这会为您提供所需的 "No:of days in Month x" 作为列表:

[24, 31, 6]

这是处理不同年份日期的强大解决方案。

def get_months_and_durations(start_date,end_date):
    current = start_date
    result = [current]

    current = current.replace(day=1)
    while current <= end_date:
        current += timedelta(days=32)
        current = current.replace(day=1)
        result.append(datetime(current.year, current.month, 1).date())

    durations= []
    for curr in result[:-1]:
        curr_range = calendar.monthrange(curr.year, curr.month)
        curr_duration = (curr_range[1] - curr.day)+1

        if ((curr.month == end_date.month) & (curr.year == end_date.year)):
            durations.append(end_date.day)
        else:
            durations.append(curr_duration)
    return result[:-1],durations