In django Rest Api model how can I calculate the age from the date of birth field i.e in backend it should work like today's date-birthdate =age but how to showcase this logic and how to do
I wrote a little util function I use for displaying any date intervals in years and months. You can adjust it for your own needs. To calculate the age from the DOB, you only need to supply the date_earlier:
def display_date_interval(date_earlier='', date_later=''):
# Set default values if blank
if not date_earlier:
date_earlier = datetime.date.today()
if not date_later:
date_later = datetime.date.today()
# Work out which date really is earlier
if date_earlier > date_later:
date_a = date_earlier
date_b = date_later
sign = '-'
else:
date_a = date_later
date_b = date_earlier
sign = ''
# Calculate the years and months
avg_days_in_month = config.AVG_DAYS_IN_YEAR / config.MONTHS_IN_YEAR
years = date_a.year - date_b.year - (
(date_a.month, date_a.day) < (date_b.month, date_b.day)
)
months = int(
(
(date_a - date_b).days - years * config.AVG_DAYS_IN_YEAR
) / avg_days_in_month,
)
return f'{sign}{years}y {months}m'
myii
William
Luis
blank_
pino@mastrobirraio ~$
Anil Kumar G
José
Dextroleav
inchidi
cj
Current
Doragonsureiyā