Django MySQL group by day with timezone

2019-05-10 23:36发布

Lets say I have a sale model:

class Sale(models.Model):
    total = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    sale_date = models.DateTimeField(auto_now_add=True)

Now, with each sale sale_date get its value saved in UTC, so if I try to group and sum all the sales by day:

report = Sale.objects.extra({'day':"date(sale_date)"}).values('day').annotate(day_total=Sum('total'))

I get all wrong becouse I expect each day in a different timezone (UTC-6).

Is there a way to get the correct sums in a specific tiemezone? Im working with MySQL.

1条回答
2楼-- · 2019-05-11 00:22

Ah, this was a good challenge. I was able to test from PostGres, and I can confirm it is working. The MySQL code should be pretty close. However, there is a note on the CONVERT_TZ documentation:

To use named time zones such as MET or Europe/Moscow, the time zone tables must be properly set up. See Section 10.6, “MySQL Server Time Zone Support”, for instructions.

MySQL (using CONVERT_TZ(dt, from_tz, to_tz))

from_tz = 'UTC'
to_tz = 'Australia/ACT'
report = Sale.objects.extra(
    {
        'day': "date(CONVERT_TZ(sale_date, '{from_tz}', '{to_tz}'))".format(
            from_tz=from_tz,
            to_tz=to_tz
         )
    }
).values(
    'day'
).annotate(
    day_total=Sum('total')
)

PostGres: (using AT TIME ZONE)

time_zone = 'Australia/ACT'
report = Sale.objects.extra(
    {'day': "date(sale_date) AT TIME ZONE '{0}'".format(time_zone)}
).values(
    'day'
).annotate(
    day_total=Sum('total')
)
查看更多
登录 后发表回答