首页 > 解决方案 > Write a python program that gives me every year from 1583 to 2017 where new year is a Monday and x-mas (24.12) is not

问题描述

I want to write a python program that gives me every year from 1583 to 2017 where new years day (1.1.) is a Monday and X-mas (24.12) is not. I want to do it with the use of datetime.

I have already tried something but as I am new to python and do not know the datetime module very well, i did not come up with a solution

import calendar

def is_ny_monday_while_xmas_not(date,weekday):
    if (calendar.weekday(date.year, date.month, 1) == "Monday":

the output should look like : 1684 1846 1934 ... (I do not know the right years so this is just an example)

标签: pythondatetime

解决方案


这是相当严格的

from datetime import date

for year in range(1583, 2018):
  if date(year, 1, 1).weekday() == 0 and date(year, 12, 24).weekday() != 0:
    print(year)

提到范围的结束,我已经从 2017 年到 2018 年更改为,因为枚举中不包含“停止”(但它没有任何改变,因为它不是星期一)。

另一个答案的良好优化(提到 4 作为 range() 的第三个参数),但要注意将其复制粘贴到另一个检查条件中。

from datetime import date

for year in range(1584, 2018, 4):
  if date(year, 1, 1).weekday() == 0 and date(year, 12, 24).weekday() != 0:
    print(year)

推荐阅读