【发布时间】:2026-02-08 23:20:02
【问题描述】:
我知道现在使用 Django 1.4 的最佳做法是将所有 datetime 存储在 UTC 中,我同意这一点。我也明白所有时区对话都应该在模板级别完成,如下所示:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
但是,我需要在 Python 中将 UTC 时间转换为 request 的本地时间。我无法使用模板标签,因为我使用 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'
})
因此,即使当前时间是 EST 时间(我的本地时区)中的 April 14, 2012, 5:52 p.m.,JSON 响应也会返回 April 14, 2012, 9:52 p.m,因为那是 UTC 时间。
我还注意到 Django 为每个请求存储了一个名为 TIME_ZONE 的模板变量(实际上不是 request 变量的一部分),所以由于我是 America/New_York,我假设 Django 可以计算出每个访问者的自己的本地时区(基于 HTTP 标头)?
无论如何,所以我的问题有两个:
- 如何在我的
ajax.py中获取访问者的本地时区? (可能将其作为字符串参数传递,例如{{ TIME_ZONE }}) - 使用访问者的本地时区,如何将 UTC
timezone.now()转换为本地时区并使用 Django 的dateformat输出为字符串?
编辑:@agf
timezone.now() 给出 USE_TZ = True 时的 UTC 时间:
# 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()
有没有办法将datetime 转换为UTC 以外的值?例如,我可以先做current_time = timezone.now(),然后再做current_time.replace(tzinfo=est)(EST = 东部标准时间)吗?
【问题讨论】: