almost a beginner almost a beginner - 2 months ago 17
Python Question

Django get months from models.DateTimeField

Is it possible to filter a models.DateTimeField but only get the month in the filter object?

The field is:

time_stamp = models.DateTimeField(
default=timezone.now)


When I filter it, this is what I get:


[datetime.datetime(2016, 9, 22, 15, 2, 48, 867473, tzinfo=),
datetime.datetime(2016, 9, 22, 15, 4, 22, 618675, tzinfo=),
datetime.datetime(2016, 9, 22, 15, 5, 20, 939593, tzinfo=)]


The filter returns 3 rows, but clearly there is too much information. I only require the months, and maybe the year.

How can I achieve this?

Any help or direction would be appreciated,

Thanks

Answer

If you are using django 1.10.x there is Extract db function

from django.db.models.functions import Extract

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)

For django 1.9.x

from django.db.models import Func

def Extract(field, date_field='DOW'):
    template = "EXTRACT({} FROM %(expressions)s::timestamp)".format(date_field)
    return Func(field, template=template)

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)
Comments