Django datetime字段 - 转换为视图中的时区 [英] Django datetime field - convert to timezone in view
问题描述
但视图怎么样?假设我需要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值,然后再发送给客户端。
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屋!