使用django查询返回活动时区中的datetimes [英] return datetimes in the active timezone with a django query

查看:82
本文介绍了使用django查询返回活动时区中的datetimes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从表中检索最后n小时的行,并在给定的时区中打印它们的日期时间,给出了打印日期时要使用的时区,我正在尝试使用Activate使django返回正确的日期时间时区,但它以UTC返回日期。

I am trying to retrieve the last n hour rows from a table and print their datetimes in a given timezone, the timezone to use when printing dates is given, I am trying to use activate to make django return the datetimes with the proper timezone but it returns dates as UTC.

这是我当前的代码:

min_time = datetime.datetime.now(link.monitor.timezone) - datetime.timedelta(hours=period)

timezone.activate(link.monitor.timezone)
rows = TraceHttp.objects.values_list('time', 'elapsed').filter(time__gt=min_time,link_id=link_id,elapsed__gt=0)

array = []
for row in rows:
    array.append((row[0].astimezone(link.monitor.timezone),row[1]))

我想避免使用astimezone函数,而让Django为我执行此操作,有时我会缺少关于Activate函数的信息吗?

I want to avoid using the astimezone function and make Django do this for me, is there sometimes I'm missing about the activate function?

编辑

这是我的模型,因为您可以看到要显示的时区保存在监视器上模型:

Here are my models, as you can see the timezone to display is saved on the "monitor" model:

class Link(models.Model):
   ...
   monitor = models.ForeignKey(Monitor)
   ...

class Monitor(models.Model):
    ...
    timezone = TimeZoneField(default='Europe/London')

class TraceHttp(models.Model):
    link = models.ForeignKey(Link)
    time = models.DateTimeField()
    elapsed = models.FloatField()


推荐答案

经过一番研究,我注意到Django始终将日期时间返回为UTC,由您决定是使用datetime.astimezone(timezone)方法还是激活某个时区来在正确的时区中解释它们。

After some research I noticed that Django allways returns datetimes as UTC and it's up to you to interpret them in the correct timezone either by using the datetime.astimezone(timezone) method or activating a certain timezone.

django活动函数只是更改日期时间将在模板上呈现的方式,但实际上并未本地化时区。

The django active function just changes the way that the datetime will be rendered on a template but doesn't actually localize a timezone.

这篇关于使用django查询返回活动时区中的datetimes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆