我知道现在使用 Django 1.4 的最佳做法是将所有内容存储datetime
在 UTC 中,我同意这一点。我也明白所有时区对话都应该在模板级别完成,如下所示:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
但是,我需要request
在 Python 中将 UTC 时间转换为本地时间。我无法使用模板标签,因为我使用 Ajax(更具体地说是Dajaxice)以 JSON 格式返回字符串。
目前这是我的代码ajax.py
:
# checked is from the checkbox's this.value (Javascript).
datetime = timezone.now() if checked else None
$ order_pk is sent to the Ajax function.
order = Order.objects.get(pk=order_pk)
order.time = datetime
order.save()
return simplejson.dumps({
'error': False,
'datetime': dateformat.format(datetime, 'F j, Y, P') if checked else 'None'
})
因此,即使当前时间是April 14, 2012, 5:52 p.m.
EST 时间(我的本地时区),JSON 响应也会返回April 14, 2012, 9:52 p.m
,因为那是 UTC 时间。
我还注意到 Django 存储了一个TIME_ZONE
为每个请求调用的模板变量(实际上不是request
变量的一部分),所以由于我的 is America/New_York
,我假设 Django 可以找出每个访问者自己的本地时区(基于 HTTP 标头)?
无论如何,所以我的问题有两个:
- 如何在我的 中获取访问者的本地时区
ajax.py
?(可能将其作为字符串参数传递,例如{{ TIME_ZONE }}
) - 使用访问者的本地时区,如何将 UTC 转换
timezone.now()
为本地时区并使用 Django 的字符串输出dateformat
?
编辑:对于@agf
timezone.now()
给出 UTC 时间USE_TZ = True
:
# From django.utils.timezone
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
反正有没有将 a 转换为datetime
UTC 以外的东西?例如,我可以执行类似current_time = timezone.now()
, then current_time.replace(tzinfo=est)
(EST = Eastern Standard Time) 的操作吗?