Django Extract Only Year from Date Time in Queryset

I have a purchases table with a column datatime. I would like to select all purchases I have done in the current year. bellow is my code but is not working!

import datetime
today = datetime.date.today()
year = Purchases.objects.filter(date__year = today.year)

I expect the year should be 2018 extracted from 2018-04-12

2 Answers

You can use ExtractYear function, here is example:

from django.db.models.functions import ExtractYear

qs = Purchases.objects.annotate(year=ExtractYear('date')).filter(year = today.year)

While querying, we can get year from model field of type DateField as fieldname__year (for comparision). If we have a field named 'purchase_date' in our model, we can filter data for a particular year as:

MyModel.objects.filter(purchase_date__year=targetyear)

In your case, if the column name is datatime. You can get the purchases done in current year as:

import datetime
today = datetime.date.today()
purchases = Purchases.objects.filter(datatime__year=today.year)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest