在Django中检索支持时区的DateTimeField [英] Retrieve timezone aware DateTimeField in Django

查看:50
本文介绍了在Django中检索支持时区的DateTimeField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我有一个 DateTimeField

In my models, I have a DateTimeField say

class ReturnEvent(models.Model):
  book_title = models.CharField()
  return_time = models.DateTimeField()

当我检索要打印的 return_time 时,例如:

When I retrieve the return_time to be printed, for example:

return_event = ReturnEvent.objects.get(id=1)
print(return_event.return_time.strftime("%H:%M"))

我看到日期时间不知道,例如:

I am seeing the datetime unaware time like:

2016-06-18 08:18:00 + 00:00

但是,我喜欢使用strftime查看本地时间.

However, I like to see the local time using strftime.

2016-06-18 10:18:00 + 02:00

对此有快速解决方案吗?

Is there a quick solution for this?

推荐答案

如果您的设置中具有 USE_TZ = True ,则Django将所有日期时间对象存储为 UTC 并在模板中呈现时将它们从 settings.py 即时转换为您的 TIME_ZONE = XYZ .

If you have USE_TZ = True in your settings, Django stores all the datetime objects in the database as UTC and convert them to your TIME_ZONE=XYZ from settings.py on the fly when rendering in the templates.

这就是为什么当从数据库中检索时, datetime 对象可以识别时区,但是它的时区为 UTC (因此, +00:00 2016-06-18 08:18:00 + 00:00 中的code>).同样,您自己将时间转换为 str (并且不在模板中呈现),因此Django不会将其转换为您的 TIME_ZONE 设置.您需要将其自己转换为所需的TimeZone.

That is why, when retrieved from the database, datetime object is timezone aware but it has UTC as its timezone (hence +00:00 in 2016-06-18 08:18:00+00:00). As, you are converting the time to str yourself (and not rendering in the template) so Django does not convert it to your TIME_ZONE setting. You need to convert it yourself to your desired TimeZone.

如果要从 TIME_ZONE 设置将其转换为TimeZone,可以执行

If you want to convert it to the TimeZone from your TIME_ZONE setting, you can do

from django.utils import timezone
to_tz = timezone.get_default_timezone()
print return_event.return_time.astimezone(to_tz).strftime("%H:%M")

这篇关于在Django中检索支持时区的DateTimeField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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