Django TruncHour不带其他日期字段

Django TruncHour不带其他日期字段,django,python-3.x,Django,Python 3.x,我有一系列爬网帖子的时间戳。现在,我想显示一个统计数据,其中显示的是文章作者的活动 为此,我想以天和小时为单位过滤帖子的时间(模型帖子包含datetime字段“timestamps”)。对天的过滤是有效的。我想显示帖子创建的时间(11:00、09:00等) 我想像这样过滤数据集 from django.db.models.functions import TruncHour from django.db.models import Count from .models import Posts

我有一系列爬网帖子的时间戳。现在,我想显示一个统计数据,其中显示的是文章作者的活动

为此,我想以天和小时为单位过滤帖子的时间(模型帖子包含datetime字段“timestamps”)。对天的过滤是有效的。我想显示帖子创建的时间(11:00、09:00等)

我想像这样过滤数据集

from django.db.models.functions import TruncHour
from django.db.models import Count
from .models import Posts

posts = Posts.objects.all()
hours = posts.annotate(hour=TruncHour('timestamp')).values('hour').annotate(count=Count('id'))
但有了这个过滤器,我会收到一系列的小时,其中包含不同的天、月、年。。。我只想收到纯小时,没有其他参数


还有路要走吗?欢迎提供任何线索……

为了获得您使用的小时,而不是截短到小时的时间

因此,您可以使用以下表达式:

from django.db.models import Count
from django.db.models.functions import ExtractHour

posts = Posts.objects.annotate(
    hour=ExtractHour('timestamp')
).values('hour').annotate(
    count=Count('id')
).order_by('hour')
SELECT EXTRACT(HOUR FROM CONVERT_TZ(post.timestamp, 'UTC', 'UTC')) AS hour,
       COUNT(post.id) AS count
FROM post
GROUP BY EXTRACT(HOUR FROM CONVERT_TZ(post.timestamp, 'UTC', 'UTC'))
ORDER BY hour ASC