Advertisement
gruntfutuk

Day_of_week

Sep 14th, 2018
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. ''' determine day of week for any Gregorian date '''
  2.  
  3. # based on formulae at https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html
  4.  
  5. DOW = dict(enumerate(('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')))
  6. MONTHS = dict(enumerate(('January', 'February', 'March', 'April',
  7.                        'May', 'June', 'July', 'August',
  8.                        'September', 'October', 'November', 'December'), start=1))
  9.  
  10.  
  11.  
  12. def is_leap_year(year):
  13.     'return True/False if year is a leap year'
  14.     return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  15.  
  16. def get_date(msg):
  17.     'get date from user and return tuple of dd, mm, yyyy'
  18.     while True:
  19.         response = input(msg).strip().split('/')
  20.         if response and len(response) == 3:
  21.             try:
  22.                 dd, mm, yyyy = [int(x) for x in response]
  23.                 if not 1 <= dd <= 31:
  24.                     raise IndexError('Day must be between 1 and 31')
  25.                 if not 1 <= mm <= 12:
  26.                     raise IndexError('Month must be between 1 and 12')
  27.                 if not 1582 <= yyyy <= 9999:
  28.                     raise IndexError('Year must be between 1582 and 9999')
  29.                 if mm == 2 and dd > 28:
  30.                     if not is_leap_year(yyyy) or dd > 29:
  31.                         raise IndexError(f'Too many days for {MONTHS[2]} in {yyyy}')
  32.                 if dd == 31 and mm not in (1, 3, 5, 7, 8, 10, 12):
  33.                     raise IndexError(f'Too many days for {MONTHS[mm]}')
  34.                 return dd, mm, yyyy
  35.             except ValueError as e:
  36.                 print(f'{response} can not be understood as a date such as 18/05/1958')
  37.             except IndexError as e:
  38.                 print(e)
  39.         else:
  40.             print('A response in the required format is expected. Please try again.')
  41.  
  42. def day_of_week(dd, mm, yyyy):
  43.     'return day of week for date dd/mm/yyyy'
  44.     mm = mm - 2  # march = 1, jan = 11
  45.     if mm < 1:
  46.         mm + 12
  47.     if mm >= 11:  # year - 1 if month is jan or feb
  48.         yyyy -= 1
  49.  
  50.     C = int(yyyy / 100)
  51.     Y = yyyy % (C * 100)
  52.     W = (dd + int(2.6 * mm - 0.2) - 2 * C + Y + int(Y/4) + int(C/4)) % 7
  53.  
  54.     return DOW[W]
  55.  
  56. dd, mm, yyyy = get_date('Please enter date of birth in form: dd/mm/yyyy: ')
  57. print(f'{dd}/{mm}/{yyyy} is a {day_of_week(dd, mm, yyyy)}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement