Advertisement
acclivity

pyFindNamedDaysForYear

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