gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:35:37 27 4
gpt4 key购买 nike

我有两个日期字段 campaign_start_datecampaign_end_date .我想计算介于 campaign_start_date 之间的每个月的天数和 campaign_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

要计算事件中涉及的月份数并获取月份列表以计算每月持续时间,您可以使用它(基于 Python: get all months in range? 中 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

它为您提供了所需的“第 x 个月的天数”作为列表:

[24, 31, 6]

关于python-2.7 - 如何在Python中获取两个日期之间特定月份的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com