Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime
- class Datestuff: # dummy class
- isleap = lambda year: year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
- @staticmethod
- def age_check(birth_date:str, cutoff_year:int=18) -> int:
- """return whole age of person given string date yyyy-mm-dd"""
- try:
- year, month, day = [int(numstr) for numstr in birth_date.split("-")]
- except ValueError:
- raise ValueError(f'{birth_date} in not in required yyyy-mm-dd format') # pass up the chain
- # further validations
- if not 1910 <= year <= datetime.now().date().year:
- raise ValueError(f'Someone born in {year} is not alive today')
- if not 1 <= month <= 12:
- raise ValueError(f'{month} is not a valid month number')
- if not 1 <= day <= 31:
- raise ValueError(f'{day} is not a valid day number')
- if month == 2 and day == 29 and not isleap(year):
- raise ValueError(f'invalid date - {year} is not a leap year')
- if (day > 29 if month == 2 else 31) and month not in [1, 3, 5,7,8,10,12]:
- raise ValueError(f'invalid date - not {day} days in month {month}')
- today = datetime.now().date()
- age = 0
- if today.year > year:
- age = today.year - year
- if today.month < month or (today.month == month and today.day < day):
- age -= 1
- return age
- @classmethod
- def is_18(cls, birth_date:str) -> bool:
- """return if age determined from birthdate yyyy-mm-dd is >= 18 """
- return cls.age_check(birth_date) >= 18
- eg = Datestuff()
- tests = ["1999/12/10", "1863-12-10", "1995-13-05", "1995-12-00",
- "2019-02-29", "2019-02-30", "2016-07-29",
- "2000-01-01", "2000-04-31"
- ]
- print('\n\nCheck for valid birthdates and return age:\n')
- for test in tests:
- try:
- print(f'Born: {test}, age: {eg.age_check(test)}')
- except ValueError as e:
- print(f'Born: {test} - ERROR: {e}')
- print('\n\nCheck for valid birthdates and confirm if age >= 18:\n')
- for test in tests:
- try:
- print(f'Born: {test}, old enough: {"yes" if eg.is_18(test) else "no"}')
- except ValueError as e:
- print(f'Born: {test} - ERROR: {e}')
Add Comment
Please, Sign In to add comment