Django datetime字段 - 转换为视图中的时区 [英] Django datetime field - convert to timezone in view

查看:227
本文介绍了Django datetime字段 - 转换为视图中的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 datetime 字段的Django模型。保存后,存储在我的 DB 中的日期时间字段将丢失时区信息,因此将其保存为 naive datetime。一般来说,这不是一个问题,因为Django会在模板中呈现datetime字段时自动将其自动转换。



但视图怎么样?假设我需要datetime服务器端的字符串表示形式。根据夏/冬时间,我的时区可能是GTM + 1或GMT + 2,这使得事情变得更加困难。



那么如何在视图中应用本地tz转换?我用pytz尝试过几种方法。没有成功,ome条目将转换为GMT + 1,而其他格式转换为GMT + 2:(



例如

  system_tz = pytz.timezone('Europe / Berlin')
local_dt = item.created_at.astimezone(system_tz)
local_dt = system_tz.normalize(local_dt)

附加信息:




  • Django 1.8.7。

  • settings.USE_TZ = True

  • MySQL

  • 这是因为我有一个通过AJAX加载所有行的表,我需要使用strftime()准备datetime值,然后再发送给客户端。

$ b $ django.utils import timezone

local_dt = timezone.localtime(item.created_at)b

解决方案

  ,pytz.timezone('Europe / Berlin')

要满足UTC + 1: p>

  from django.utils import timezone 

local_dt = timezone.localtime(item.created_at,timezone.get_f ixed_timezone(60)




I have a Django model with a datetime field. When it is saved, the datetime field stored in my DB lose the timezone info, so it's saved as a naive datetime. In general this is not a problem since Django converts it back automatically when rendering the datetime field in the template.

But what about the view? Let's say I need the string representation of the datetime server-side. Depending on summer/winter time, my timezone could be GTM+1 or GMT+2, what makes the things more difficult.

So how do I apply the local tz conversion in the view? I have tried several ways with pytz. No success, ome entries are converted to GMT+1 and others to GMT+2 :(

Eg.

system_tz = pytz.timezone('Europe/Berlin')
local_dt = item.created_at.astimezone(system_tz)
local_dt = system_tz.normalize(local_dt)

Additional info:

  • Django 1.8.7.
  • settings.USE_TZ = True
  • MySQL
  • Why am I doing this? Because I have a table which loads all its rows on demand through AJAX. I need to prepare the datetime values with strftime() before send them to the client.

解决方案

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, pytz.timezone('Europe/Berlin'))

To conevert to UTC+1:

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, timezone.get_fixed_timezone(60)

这篇关于Django datetime字段 - 转换为视图中的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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