[英]How can I determine the weekday of a leap day?
I am trying to figure out what day of the week the leap day falls under (ex. Sunday, Monday, etc) for each year (ex. 1972 Tuesday) in a range of years.我试图弄清楚闰日在几年中的每一年(例如 1972 年星期二)属于一周中的哪一天(例如星期日、星期一等)。
The code below checks that each year is a leap year and appends it to an array:下面的代码检查每年是否是闰年并将其附加到数组中:
import array as year
LeapYear = []
startYear = 1970
endYear = 1980
for year in range(startYear, endYear):
if (0 == year % 4) and (0 != year % 100) or (0 == year % 400):
LeapYear.append(year)
print(year)
You are kind of reinventing the wheel.你是在重新发明轮子。 You can use
calendar.isleap
to determine if a year is a leap year.您可以使用
calendar.isleap
来确定一年是否为闰年。 To get the zero-indexed day of the week (with the week starting on Mondays), you can use calendar.weekday
.要获取一周中的零索引日(一周从星期一开始),您可以使用
calendar.weekday
。
import calendar
days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
start = 1994
end = 2025
for year in range(start, end):
if calendar.isleap(year):
day_ix = calendar.weekday(year, 2, 29)
print(year, days[day_ix])
# prints:
1996 Thu
2000 Tue
2004 Sun
2008 Fri
2012 Wed
2016 Mon
2020 Sat
2024 Thu
You can use datetime.date
to a) check if Feb 29 exists and b) get its weekday name .您可以使用
datetime.date
a) 检查是否存在 Feb 29 和 b) 获取其工作日名称。
from datetime import date
for year in range(1970, 1980):
try:
leap_day = date(year, 2, 29)
except ValueError:
# Not a leap year
continue
weekday = leap_day.strftime('%A')
print(year, weekday)
Output: Output:
1972 Tuesday
1976 Sunday
Here I'm using EAFP style, but LBYL would also work perfectly fine, ie这里我使用的是EAFP风格,但LBYL也可以正常工作,即
if calendar.isleap(year):
leap_day = date(year, 2, 29)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.