[英]Calculate how many Monday the 1st between two dates
Is it possible to calculate how many Monday the 1st are between two dates? 是否可以计算两个日期之间的第一天有多少个星期一?
I wrote two functions to find how many days are between two dates, using C++: 我使用C ++编写了两个函数来查找两个日期之间有多少天:
int rdn(int y, int m, int d) {
if (m < 3) { y--, m += 12; };
return 365*y + y/4 - y/100 + y/400 + (153*m - 457)/5 + d - 306;
}
int days = rdn(2015, 01, 01) - rdn(2015, 12, 31);
And using Python: 并使用Python:
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
print(days_between('2015-01-01', '2015-12-31'))
But I don't understand how to update my function to calculate Monday the 1st. 但是我不明白如何更新我的函数来计算星期一1号。
This algorithm is a loop that examines the weekday of the 1st of each month from the start date (inclusive) to the end date (inclusive), and counts the ones which fall on a Monday: 此算法是一个循环,它检查从开始日期(含)到结束日期(含)的每个月的1号的工作日,并计算落在星期一的日期:
import datetime
def num_monday_the_first_between(start, end):
y, m, d = start.year, start.month, 1
count = 0
while (y, m, d) <= (end.year, end.month, end.day):
if datetime.date(y, m, d).isoweekday() == 1:
count += 1
m += 1
if m == 13:
m = 1
y += 1
return count
print(num_monday_the_first_between(datetime.date(2015,1,1), datetime.date(2015,12,31)))
# Result: 1 (June)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.