Last active
July 30, 2022 11:03
-
-
Save mezhgano/05722a5c8817a7ea610557eb745bc524 to your computer and use it in GitHub Desktop.
Calculate age from given date string with prefix and postfix (RU)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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