简体   繁体   中英

Compare datetime with Django birthday objects

I have a question about my script. I want to know all people who have more than 16 years from my Database. I want to check this when user triggers the function.

I have this function :

def Recensement_array(request) :

    date = datetime.now().year
    print date # I get year from now

    birthday = Identity.objects.values_list('birthday', flat=True) # Return list with all birthday values

    for element in birthday :
        if date - element < 117 : 
            print "ok < 117"

        else : 
            print "ok > 117"

From print date I get :

2017

From print birthday I get :

<QuerySet [datetime.date(1991, 12, 23), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1990, 12, 12)]>

So my goal is to substract date with birthday and compare if date - birthday = 16 years , I print element, else nothing.

I get two problems :

  • How extract only year from birthday ?
  • Then the comparison method is between int and tuple up to now. If I could extract only year from birthday, it should work right ?

Thank you

EDIT :

For example I want to get all people who had 16 years old since the begining of this year or will get 16 years old before the first year :

def Recensement_array(request) :

    today = datetime.now()
    age_16 = (today - relativedelta(years=16))

    result = Identity.objects.filter(birthday__range=[age_16, today]).order_by('lastname')

    paginator = Paginator(result, 3)
    page = request.GET.get('page', 1)

    try:
        result = paginator.page(page)
    except PageNotAnInteger:
        result = paginator.page(1)
    except EmptyPage:
        result = paginator.page(paginator.num_pages)

    context = {
    "Identity":Identity,
    "age_16":age_16,
    "datetime" : datetime,
    "result" : result,
    "PageNotAnInteger":PageNotAnInteger,
    }


    return render(request, 'Recensement_resume.html', context)

If you need filter records with some specific year you can just use __year method of date field:

age_16 = (today - relativedelta(years=16))
result = Identity.objects.filter(birthday__year=age_16.year).order_by‌​('last‌​name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM