1

I have two dates:

  1. A query set from a database which includes a date field (1992-11-15) and date.today()

Here is my views.py

    def pop(request):
    start = randint(0, 2)
    finish = randint(2, 5)
    current_year = [date.today().year, date.today().year]
    context = {
        'alluserprofiles': zip(Profile.objects.all()[start:finish], 
    current_year),
        'maleuserprofiles': zip(Profile.objects.filter(gender='male'), current_year),
        'femaleuserprofiles': zip(Profile.objects.filter(gender='female'), current_year),
        'start': start,
        'finish': finish
    }
    return render(request, 'users/pop.html', context)

And here is my django template

   {% for profile, year in alluserprofiles %}
<div class="container fixed-top" id="pop-up">
  <div class="card text-center border-light mb-3">
    <img class="card-img-top" src="{{ profile.image_prof.url }}" />
    <div class="card-body">
            <h5> {{ profile.user }} {{ year|sub:profile.birthday.year}}

How can I subtract them to get exact age? I am able only to manage year subtraction.

Thanks a lot

Arthur
  • 109
  • 8
  • 1
    Possible duplicate of [Subtracting Dates With Python](https://stackoverflow.com/questions/12126318/subtracting-dates-with-python) – Jake P Aug 05 '19 at 18:35

3 Answers3

2

Duplicated of: Subtracting Dates With Python

from datetime import datetime

birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329

(sorry, i can only answer, because i don't have enough reputation)

notihs
  • 654
  • 7
  • 19
0

something like below,

import datetime

def age_calc(dob):
   return date.today().year - dob.year - ((date.today().month, date.today().day) < (dob.month, dob.day))
Anup
  • 250
  • 1
  • 6
0

Here is the solution

{{ profile.birthday|timesince:year|slice:":2" }}

slicing in the end to get age digits

Arthur
  • 109
  • 8