Django get months from models.DateTimeField
<p>Is it possible to filter a models.DateTimeField but only get the month in the filter object?</p>

<p>The field is:</p>

<pre><code>time_stamp = models.DateTimeField(
            default=timezone.now)
</code></pre>

<p>When I filter it, this is what I get:</p>

<blockquote>
  <p>[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=)]</p>
</blockquote>

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

<p>How can I achieve this?</p>

<p>Any help or direction would be appreciated,</p>

<p>Thanks</p>

<p>If you are using django 1.10.x there is <a href="https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#extract" rel="nofollow"><code>Extract</code></a> db function</p>

<pre><code>from django.db.models.functions import Extract

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)
</code></pre>

<p>For django 1.9.x</p>

<pre><code>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)
</code></pre>

python django datetime