姜戈 |查询时Datetime的时间发生变化
Django | Datetime's time changes when doing the query
我正在尝试查询一个日期范围。查看 Django 生成的查询,我发现它没有占用 datetime
的时间
这是我的代码
tz = pytz.timezone('Europe/London')
today = datetime.now(tz=tz)
week_end = today.replace(hour=23,minute=59,second=59,microsecond=0)
day_start = today - timedelta(6)
week_start = day_start.replace(hour=0, minute=0, second=0, microsecond=0)
ultimas_transferencias = Transferencia.objects.filter(fecha__gte=week_start,
fecha__lte=week_end, estatus__id=1)\
.extra(select={'dia': 'DAY(fecha)'}).order_by().values('dia') \
.annotate(total=Sum('monto')).values('dia', 'total').annotate(numero=Count('pk')).values('dia', 'total','numero')
print(ultimas_transferencias.query)
return JsonResponse({'data': list(ultimas_transferencias)})
这是查询:
SELECT (DAY(fecha)) AS `dia`, SUM(`remesasapp_transferencia`.`monto`) AS `total`, COUNT(`remesasapp_transferencia`.`id`) AS `numero`
FROM `remesasapp_transferencia`
WHERE (`remesasapp_transferencia`.`estatus_id` = 1 AND
`remesasapp_transferencia`.`fecha` >= 2020-08-23 23:00:00
AND `remesasapp_transferencia`.`fecha` <= 2020-08-30 22:59:59) GROUP BY (DAY(fecha)) ORDER BY NULL
注意时间显示为 2020-08-23 23:00:00 而不是 2020-08-23 00:00:00
我找到了解决方案。我今天用的不是 today = datetime.now(tz=tz)
= timezone.now()
我正在尝试查询一个日期范围。查看 Django 生成的查询,我发现它没有占用 datetime
这是我的代码
tz = pytz.timezone('Europe/London')
today = datetime.now(tz=tz)
week_end = today.replace(hour=23,minute=59,second=59,microsecond=0)
day_start = today - timedelta(6)
week_start = day_start.replace(hour=0, minute=0, second=0, microsecond=0)
ultimas_transferencias = Transferencia.objects.filter(fecha__gte=week_start,
fecha__lte=week_end, estatus__id=1)\
.extra(select={'dia': 'DAY(fecha)'}).order_by().values('dia') \
.annotate(total=Sum('monto')).values('dia', 'total').annotate(numero=Count('pk')).values('dia', 'total','numero')
print(ultimas_transferencias.query)
return JsonResponse({'data': list(ultimas_transferencias)})
这是查询:
SELECT (DAY(fecha)) AS `dia`, SUM(`remesasapp_transferencia`.`monto`) AS `total`, COUNT(`remesasapp_transferencia`.`id`) AS `numero`
FROM `remesasapp_transferencia`
WHERE (`remesasapp_transferencia`.`estatus_id` = 1 AND
`remesasapp_transferencia`.`fecha` >= 2020-08-23 23:00:00
AND `remesasapp_transferencia`.`fecha` <= 2020-08-30 22:59:59) GROUP BY (DAY(fecha)) ORDER BY NULL
注意时间显示为 2020-08-23 23:00:00 而不是 2020-08-23 00:00:00
我找到了解决方案。我今天用的不是 today = datetime.now(tz=tz)
= timezone.now()