简体   繁体   English

如何确定闰日的工作日?

[英]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.

相关问题 我怎样才能找到某个工作日的第二天(例如,下一次是星期一)? - How can I find the next day that will be a certain weekday (the next time it will be Monday, for instance)? 如何创建没有a日的日期时间列表? - How to create list of datetimes without a leap day? 如何判断某年是否为闰年? - How to determine whether a year is a leap year? 如何将leap年纳入年龄计算器? - How can I incorporate leap years in an age calculator? 如何使用 Python 检查年份是否为闰年? - How can I check if a year is a leap year using Python? 在pandas中,如何将dayday()分组为datetime列? - in pandas how can I groupby weekday() for a datetime column? 确定该月给定日期的星期几。 给定月份第一天的工作日 - Determine the day of the week of the given date in that month. Given the weekday of the first day of the month 如果日期是工作日,则获取当前日期,否则获取最近的工作日(即星期五)的日期 - Get current date if day is weekday, else get date of most recent weekday (i.e., Friday) 气流:如何安排 dag 在工作日的第二天开始? - Airflow: how to schedule a dag to start the day following a weekday? 如何判断天气一年是闰年,之后的年份是Python? - How to determine weather a year is a leap year, and the years thereafter in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM