Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display date of birth in django app

Tags:

python

django

How to display age from dob obtained? Any suggestion?

models.py

from django.db import models
import datetime

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
        age = today.year - dob.year
    if today.month < dob.month or today.month == dob.month and today.day < dob.day:
        age -= 1
    return self.age 

Thank you, Rads

like image 328
Rads Avatar asked Oct 16 '25 13:10

Rads


1 Answers

You should use the python-dateutil to get the relativedelta between dates:

from dateutil.relativedelta import relativedelta
from django.db import models

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
    delta = relativedelta(today, self.dob)
    return str(delta.years)
like image 121
mipadi Avatar answered Oct 19 '25 06:10

mipadi