Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django从models.DateTimeField获得月数_Python_Django_Datetime - Fatal编程技术网

Python Django从models.DateTimeField获得月数

Python Django从models.DateTimeField获得月数,python,django,datetime,Python,Django,Datetime,是否可以筛选models.DateTimeField,但只获取筛选对象中的月份 该字段为: time_stamp = models.DateTimeField( default=timezone.now) 当我过滤它时,我得到的是: [datetime.datetime(2016,9,22,15,2,48,867473,tzinfo=), datetime.datetime(2016,9,22,15,4,22,618675,tzinfo=), datetime.date

是否可以筛选models.DateTimeField,但只获取筛选对象中的月份

该字段为:

time_stamp = models.DateTimeField(
            default=timezone.now)
当我过滤它时,我得到的是:

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

过滤器返回3行,但显然信息太多。我只需要几个月,也许是一年

我怎样才能做到这一点

任何帮助或指导都将不胜感激

谢谢

您可以使用Property:

Class your_model(models.Model):

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

    @property
    def _get_year(self):
        return self.time_stamp.strftime("%Y-%m")

    year = property(_get_year) #EDIT

如果您使用的是django 1.10.x,则有db函数

from django.db.models.functions import Extract

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)
对于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)

1.如果它是一个方法,则可以将其称为
get_year
,但对于属性,只需将其称为
year
。2.请注意,这只适用于实例,而不适用于QuerySets。要进行查询,可以执行以下操作:月=结果。值\u列表('get\u year',flat=True)谢谢你的精心设计,就像我说的,它在queryset中不起作用。您必须改为使用理解,或更改字段。@wim如何更改字段以仅使用datetime存储当前月份和年份。datetime??默认的timzone.now在我的情况下是无用的。@Windsooon当我筛选年份时,我得到“无法将关键字'year'解析到字段中”。我想正如wim所说,您不能查询属性。