Home > Mobile >  How can I determine the weekday of a leap day?
How can I determine the weekday of a leap day?

Time:01-22

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.

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)

CodePudding user response:

You are kind of reinventing the wheel. You can use calendar.isleap to determine if a year is a leap year. To get the zero-indexed day of the week (with the week starting on Mondays), you can use 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

CodePudding user response:

You can use datetime.date to a) check if Feb 29 exists and b) get its weekday name.

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:

1972 Tuesday
1976 Sunday

Here I'm using EAFP style, but LBYL would also work perfectly fine, i.e.

if calendar.isleap(year):
    leap_day = date(year, 2, 29)
    ...
  •  Tags:  
  • Related