Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django extract only year from date time in queryset

Tags:

python

django

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

like image 917
Rafa Avatar asked Apr 18 '18 19:04

Rafa


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)
like image 87
Grigoriy Mikhalkin Avatar answered Oct 02 '22 15:10

Grigoriy Mikhalkin


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)
like image 27
Ganesh Negi Avatar answered Oct 02 '22 16:10

Ganesh Negi