Skip to content

Instantly share code, notes, and snippets.

@mezhgano
Last active July 30, 2022 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mezhgano/05722a5c8817a7ea610557eb745bc524 to your computer and use it in GitHub Desktop.
Save mezhgano/05722a5c8817a7ea610557eb745bc524 to your computer and use it in GitHub Desktop.
Calculate age from given date string with prefix and postfix (RU)
def age_str_calc(date: str, strp_format: str, bounds=(1, 120)) -> tuple:
'''Calulate age from given date, if age fit the bounds (default is 1-120 years),
then return string: prefix (RU) + age (in years) + postfix (RU). Otherwise return empty string.'''
def age(birthdate: object) -> int:
'''Return age (int) by given datetime object'''
today = datetime.date.today()
age = today.year - birthdate.year - (
(today.month, today.day) < (birthdate.month, birthdate.day)
)
return age
age = age(dt.strptime(date, strp_format).date())
if age < bounds[0] or age > bounds[1]:
return ''
else:
prefix = 'Возраст:'
if 5 <= age <= 20:
postfix = 'лет'
elif int(repr(age)[-1]) % 10 == 1:
postfix = 'год'
elif 2 <= int(repr(age)[-1]) % 10 <= 4:
postfix = 'года'
else:
postfix = 'лет'
return ' '.join((prefix, str(age), postfix))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment