# Average age from birth date

**URL:** <https://forum.djangoproject.com/t/average-age-from-birth-date/2454>\
**Category:** Using Django\
**Created:** [May 15, 2020, 9:42am UTC](https://forum.djangoproject.com/t/average-age-from-birth-date/2454 "2020-05-15T09:42:57Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![smrashel](https://avatars.discourse-cdn.com/v4/letter/s/f08c70/32.png) [@smrashel](https://forum.djangoproject.com/u/smrashel)\
**Post date:** [May 15, 2020, 9:42am UTC](https://forum.djangoproject.com/t/average-age-from-birth-date/2454/1 "2020-05-15T09:42:57Z")

</div>

In my django(3.0.5) application I am trying to get average age from date of birth in a model. In MySql database table birth\_date stores data in ‘1980-01-15’ format. Here is how I tried:

```
class ShippingStaff(models.Model):
    full_name = models.CharField('Full Name', max_length=200)
    birth_date = models.DateField('Date of Birth', null=True, blank=True)

@register.filter(name='age')
def age(bday, d=None):
    bday = datetime.strptime(bday, '%Y-%m-%d')
    if d is None:
        d = datetime.date.today()
    return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day))

def home(request):
shipping_staff = ShippingStaff.objects.aggregate(staff_count=Count('full_name'),
                                                 avg_age=Avg(custom_time.age('birth_date'))

```

| Exception Type: | ValueError |
| --- | --- |
| Exception Value: | time data ‘birth\_date’ does not match format ‘%Y-%m-%d’ |

How can I solve this? Any help will be much appreciated.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [May 15, 2020, 12:48pm UTC](https://forum.djangoproject.com/t/average-age-from-birth-date/2454/2 "2020-05-15T12:48:56Z")

</div>

Depending upon how precise I needed to be, my first thought would be to use the MySql-provided [datediff function](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_datediff) to calculate each person’s age in days and average them, then convert that to a year-month-day value. What I don’t know is how I would code that in terms of an ORM query. I know you can define custom functions for the ORM to use in building queries, but I’ve never done it myself.

As a side note - and it’s perhaps a little pedantic - but MySql stores a date field [internally as a 3-byte value](https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html#data-types-storage-reqs-date-time). MySql translates it to the YYYY-MM-DD format when being selected.

---

<div class="post-metadata">

**Author:** ![smrashel](https://avatars.discourse-cdn.com/v4/letter/s/f08c70/32.png) [@smrashel](https://forum.djangoproject.com/u/smrashel)\
**Post date:** [May 15, 2020, 5:13pm UTC](https://forum.djangoproject.com/t/average-age-from-birth-date/2454/3 "2020-05-15T17:13:09Z")

</div>

Thanks for the hint.  
I ended up with a solution below:

from django.db import connection

```
with connection.cursor() as cursor:
    cursor.execute("select ROUND(AVG(DATEDIFF(CURDATE(), birth_date) / 365.25), 2) as avg_age 
                            FROM crewdatabd_shippingstaff")
    age = cursor.fetchone()

in template:
    {{age.0}}
```

---

<div class="post-metadata">

**Author:** ![uhurusurfa](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/uhurusurfa/32/3958_2.png) [@uhurusurfa](https://forum.djangoproject.com/u/uhurusurfa)\
**Post date:** [September 13, 2021, 6:10pm UTC](https://forum.djangoproject.com/t/average-age-from-birth-date/2454/4 "2021-09-13T18:10:18Z")

</div>

```auto
from django.db.models.functions import ExtractYear
from django.utils import timezone
current_year = timezone.now().year
ShippingStaff.objects.aggregate(average_age=Avg(current_year - ExtractYear('birth_date')))

```

You could just get the DB to calculate the current year in the same way but my guess is it is probably more efficient this way
