gruntfutuk

Check Age

Jul 18th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. from datetime import datetime
  2.  
  3. class Datestuff:  # dummy class
  4.    
  5.     isleap = lambda year: year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  6.    
  7.     @staticmethod
  8.     def age_check(birth_date:str, cutoff_year:int=18) -> int:
  9.         """return whole age of person given string date yyyy-mm-dd"""
  10.         try:
  11.             year, month, day = [int(numstr) for numstr in birth_date.split("-")]
  12.         except ValueError:
  13.             raise ValueError(f'{birth_date} in not in required yyyy-mm-dd format')  # pass up the chain
  14.        
  15.         # further validations
  16.         if not 1910 <= year <= datetime.now().date().year:
  17.             raise ValueError(f'Someone born in {year} is not alive today')
  18.         if not 1 <= month <= 12:
  19.             raise ValueError(f'{month} is not a valid month number')
  20.         if not 1 <= day <= 31:
  21.             raise ValueError(f'{day} is not a valid day number')
  22.         if month == 2 and day == 29 and not isleap(year):
  23.             raise ValueError(f'invalid date - {year} is not a leap year')
  24.         if (day > 29 if month == 2 else 31) and month not in [1, 3, 5,7,8,10,12]:
  25.             raise ValueError(f'invalid date - not {day} days in month {month}')
  26.                
  27.         today = datetime.now().date()
  28.  
  29.         age = 0
  30.         if today.year > year:
  31.             age = today.year - year
  32.             if today.month < month or (today.month == month and today.day < day):
  33.                 age -= 1
  34.  
  35.         return age
  36.    
  37.     @classmethod
  38.     def is_18(cls, birth_date:str) -> bool:
  39.         """return if age determined from birthdate yyyy-mm-dd is >= 18 """
  40.         return cls.age_check(birth_date) >= 18
  41.  
  42. eg = Datestuff()
  43. tests = ["1999/12/10", "1863-12-10", "1995-13-05", "1995-12-00",
  44.          "2019-02-29", "2019-02-30", "2016-07-29",
  45.          "2000-01-01", "2000-04-31"
  46.         ]
  47. print('\n\nCheck for valid birthdates and return age:\n')
  48. for test in tests:
  49.     try:
  50.         print(f'Born: {test}, age: {eg.age_check(test)}')
  51.     except ValueError as e:
  52.         print(f'Born: {test} - ERROR: {e}')
  53.  
  54. print('\n\nCheck for valid birthdates and confirm if age >= 18:\n')      
  55. for test in tests:
  56.     try:
  57.         print(f'Born: {test}, old enough: {"yes" if eg.is_18(test) else "no"}')
  58.     except ValueError as e:
  59.         print(f'Born: {test} - ERROR: {e}')
Add Comment
Please, Sign In to add comment