0

In my django(3.0.5) application I am trying to get average age from date of birth in a model. I am using MySql database. Here is how I tried:

Model:

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

Customer Filter:

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

Views:

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

I get error like:

Exception Value:    
'str' object has no attribute 'year'
Exception Location: /home/smrashel/jahaji/crewdatabd/templatetags/custom_time.py in age, line 31
which is

return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day))

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

1 Answers1

0

You need to change str to date. So you could use datetime.strptime like this:

from datetime import datetime

datetime_str = '08/12/12'

d = datetime.strptime(datetime_str, '%m/%d/%y')


print(d.year)
>>> 2012

In your case:

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

Of course it depends how your str date looks like, you need to adapt it to your needs

ImustAdmit
  • 388
  • 4
  • 14
  • In MySql database my birth_date is like '1985-01-15'. I tried bday = datetime.strptime(bday, '%Y-%m-%d'). Now I get: time data 'birth_date' does not match format '%Y-%m-%d'. – S. M. Rashel May 15 '20 at 10:22
  • then use ```d = datetime.strptime(datetime_str, '%Y-%m-%d')``` – ImustAdmit May 15 '20 at 10:28
  • Here is my updated filter: @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)) I still get the error: Exception Type: ValueError Exception Value: time data 'birth_date' does not match format '%Y-%m-%d' – S. M. Rashel May 15 '20 at 10:45
  • ```strptime``` have to receive date in format '1985-01-15' where 1985 is year, 01 month and 15 day. If you pass date in other format this Exception is raised. Also if month will be out of range like '1985-14-14' this same Exception will appear. Make sure that everywhere you have date in the same format. – ImustAdmit May 15 '20 at 10:52