我有一个日期范围,我需要知道这两个日期之间有多少个星期天。有没有比整天循环并检查是否是周日更好的方法?
from datetime import datetime
first_date = '2021-01-01'
final_date = '2021-01-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
我的意思是,正如你所知,一周通常不会跳过天数,你可以比较开始日期和结束日期,得到该范围内的天数,然后除以7(整数除法//(,那么你已经得到了完整的周数,也就是星期日的数量,所以你现在只需要检查星期日的剩余天数。
from datetime import datetime, timedelta
first_date = "2021-01-01"
final_date = "2021-01-31"
first_date = datetime.strptime(first_date, "%Y-%m-%d")
last_date = datetime.strptime(final_date, "%Y-%m-%d")
days = (last_date-first_date).days
num_sun = days//7
if (days % 7 + first_date.isoweekday()) >= 7:
num_sun+=1
显然,等工作日的编号是从星期一=1到星期日=7。因此,如果我没有在某个地方搞砸我的计算,那么周编号的start_day+left_overdays应该小于7。
使用while循环遍历日期,最后在第一个日期上加一天。要获取星期几,请使用weekday
方法。
from datetime import datetime, timedelta
first_date = "2021-01-01"
final_date = "2021-01-31"
first_date = datetime.strptime(first_date, "%Y-%m-%d")
last_date = datetime.strptime(final_date, "%Y-%m-%d")
delta = timedelta(days=1) # looping interval
sundays = 0
while first_date <= last_date: # or use `<` if you don't want it inclusive
if first_date.weekday() == 6:
sundays += 1
first_date += delta
print(sundays)
您只需要找到该范围内的最后一个和第一个星期日,然后找到它们之间的周数。下的示例
from datetime import datetime, timedelta
first_date = '2021-01-01'
final_date = '2021-01-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
# Identify the fist sunday from start date
first_sunday = first_date + timedelta(days=6 - first_date.weekday())
# Identify the last sunday from end date
last_sunday = last_date - timedelta(days=6 - last_date.weekday())
# Get the gap between the two dates and find the number of weeks
total_sundays = (last_sunday - first_sunday).days // 7 + 1
print(total_sundays)
给出输出
5
这是一个解决方案,包括开始和结束日期。如果要避免包含,请相应地调整计数。
主题的变体:
from datetime import datetime
def sundays(d1, d2):
df1 = datetime.strptime(d1, '%Y-%m-%d')
df2 = datetime.strptime(d2, '%Y-%m-%d')
return (df2 - df1).days // 7 + ((df1.weekday() == 6) | (df2.weekday() == 6))
print(sundays('2021-01-1', '2021-01-31'))
print(sundays('2021-01-4', '2021-01-31'))
print(sundays('2021-01-4', '2021-01-30'))
输出:
5
4
3