python - 获取特定月份中某个日期范围内的天数
问题描述
一直没能找到这个问题的答案。基本上我想要做的是:
取一个日期范围,例如 10 月 10 日到 11 月 25 日。确定日期范围中有多少天在 10 月和有多少在 11 月的最佳算法是什么。
像这样的东西:
def daysInMonthFromDaterange(daterange, month):
# do stuff
return days
我知道这很容易实现,我只是想知道是否有一个非常好的或有效的算法。
谢谢
解决方案
从这个答案中借用算法如何在 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
推荐阅读
- java - 页面对象模型类中的 NullPointerException
- python - Pandas 数据框将日期从 int64 更改为 datetime 中的日期
- linux - 即使登录有效,Pam_unix sshd 身份验证失败?
- php - 将运输标签打印到热敏打印机
- docker - 使用 docker 在 tensorflow 上调试的简单方法是什么?
- json - 使用代号一显示图像
- c# - if else condition in asp.net
- python - 创建文本图层 psd
- javascript - PDF 工具栏禁用
- java - AutoCompleteTextView 建议无法更新?