1

I am trying to do this in views.py

ExtractYear(date_of_birth) - today.year

But it gives error to use int, and i tried like:

int (ExtractYear(date_of_birth) )- int(today.year)

and it gives error of int() argument must be a string, a bytes-like object or a number, not 'ExtractYear'

and also if i try to do this:

date_of_birth_year - today.year

it gives error of name 'date_of_birth_year' is not defined

also i did:

import datetime

I just wanted to find age of person in integer and i don't know how to extract year, hours etc things in datefield or datetime field kindly help.

None
  • 35
  • 6
  • The age of a person does not only depends on the year. For example if a person is born on the first of February, then in January, he is one year younger than in March for example. – Willem Van Onsem Jul 05 '20 at 15:03
  • I just wanted to extract year, this thing is not my preference yet. – None Jul 05 '20 at 15:07

2 Answers2

1

The age of a person does not only depends on the year. For example, if a person is born on the first of February, then the first of January, he/she is one year younger than the first of March.

You can annotate your person with:

from django.db.models.functions import ExtractYear

MyModel.objects.annotate(
    date_of_birth_year=ExtractYear('date_of_birth_year')
)

The MyModels that arise from this queryset will have an extra attribute .date_of_birth_year that contains the year of the date_of_birth. You can also annotate a field age that contains the "age" of the person:

from django.db.models.functions import ExtractYear
from django.utils.timezone import now

MyModel.objects.annotate(
    age=now().year - ExtractYear('date_of_birth_year')
)

But this age is thus not exactly correct.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

Another possible solution could be:

from django.db.models import F, ExpressionWrapper
from django.db.models.functions import Now 

Model.objects.annotate(
    delta = ExpressionWrapper(
    Now() - F('date_of_birth'), output_field=models.DateTimeField()
  )
)

Then, the instance.delta will be datetime.timedelta(..) instance, a little bit math needed for further processing. Also, Django doc has a similar example, check it out

minglyu
  • 2,958
  • 2
  • 13
  • 32