Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Find all occurrences of a specified day of the week, for any year from 1901 to 2099
- def find_days(yyyy, sday): # yyyy is the year, sday is the alphabetic day e.g. "Mon"
- sdtab = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
- if sday.lower() not in sdtab or yyyy < 1901 or yyyy > 2099:
- print("Invalid day or year")
- return False
- da = sdtab.index(sday.lower()) # convert alphabetic day to index 0 to 6 (mon to sun)
- yd = yyyy - 1901 # get year offset from 1901
- leaps = yd // 4 # compute number of leap years that have occurred since 1901
- # 01-01-1901 = Monday. 01-01-1902 = Tuesday etc, but we skip an extra day each leap year
- yd = (yd + leaps) % 7 # Compute index to first day of the year in question
- dd = ((da - yd) + 7) % 7 # Find the 1st date in January for the day of week required
- days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- if not yyyy & 3: # We are only dealing with 1901 to 2099 so this simple leap test is OK
- days[2] = 29 # Modifiy days table for February if it's a leap year
- mm = 1 # Start a loop with month starting at 1
- while mm < 13: # Loop until we go past December
- if dd > 0:
- print(sday, yyyy, mm, dd)
- dd += 7 # Bump day by 7
- if dd > days[mm]: # Check for beyond month end and move into next month
- dd -= days[mm]
- mm += 1
- find_days(2021, "Sun")
- find_days(1942, "Sun")
- find_days(1947, "Sat")
- # Samples from results:-
- # Sun 2021 3 28
- # Sun 1942 7 19
- # Sat 1947 3 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement