📜  计算给定年份范围内特定工作日的日期的Python程序

📅  最后修改于: 2022-05-13 01:55:27.701000             🧑  作者: Mango

计算给定年份范围内特定工作日的日期的Python程序

给定一个日期,我们的任务是获取工作日索引和年份范围,计算该日期在年份范围内特定工作日的总出现次数。

例子:

方法 1:使用循环+ 工作日()

在这里,我们运行一个从开始年到结束年的嵌套循环,并且在每一年中,每个月都根据需要检查一个日期以精确到工作日,如果找到,则计数器递增。

Python3
# Python3 code to demonstrate working of
# Count date on weekday in Year Range
# Using loop + weekday()
from datetime import datetime
  
# initializing date
date = 13
  
# initializing weekday
weekdy = 5
  
# initializing range of Years
strt, end = 1950, 2020
  
# printing Number
print("The date, weekday : " + str(date) + " " + str(weekdy))
  
res = 0
for year in range(strt, end + 1):
  
    # checking each month for same date
    # weekday combination
    for month in range(1, 13):
        if datetime(year, month, date).weekday() == weekdy:
            res += 1
  
# printing result
print("Total dates with same weekday : " + str(res))


Python3
# Python3 code to demonstrate working of
# Count date on weekday in Year Range
# Using sum() + generator expression
from datetime import datetime
  
# initializing date
date = 13
  
# initializing weekday
weekdy = 5
  
# initializing range of Years
strt, end = 1950, 2020
  
# printing Number
print("The date, weekday : " + str(date) + " " + str(weekdy))
  
# sum performs accumulation
res = sum(datetime(year, month, date).weekday() == weekdy
          for year in range(strt, end + 1) for month in range(1, 13))
  
# printing result
print("Total dates with same weekday : " + str(res))


输出:

The date, weekday : 13 5
Total dates with same weekday : 120

方法 2:使用sum() +生成器表达式

与上述方法类似,唯一的区别是生成器表达式用于嵌套循环的任务,sum() 执行对正确找到的年月组合求和的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Count date on weekday in Year Range
# Using sum() + generator expression
from datetime import datetime
  
# initializing date
date = 13
  
# initializing weekday
weekdy = 5
  
# initializing range of Years
strt, end = 1950, 2020
  
# printing Number
print("The date, weekday : " + str(date) + " " + str(weekdy))
  
# sum performs accumulation
res = sum(datetime(year, month, date).weekday() == weekdy
          for year in range(strt, end + 1) for month in range(1, 13))
  
# printing result
print("Total dates with same weekday : " + str(res))

输出:

The date, weekday : 13 5
Total dates with same weekday : 120