如何获取访问者的当前时区,然后将timezone.now()转换为Django 1.4中本地时间的字符串? [英] How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?

查看:364
本文介绍了如何获取访问者的当前时区,然后将timezone.now()转换为Django 1.4中本地时间的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Django 1.4中最好的做法是在UTC中存储所有的 datetime ,我同意这一点。我也明白,所有的时区对话应该在模板级别完成,如下所示:

  {%load tz%} 

{%时区欧洲/巴黎%}
巴黎时间:{{value}}
{%endtimezone%}

但是,我需要将UTC时间转换为Python中的请求的本地时间。我不能使用模板标签,因为我使用Ajax(更具体地说是 Dajaxice )返回JSON中的字符串。



目前这是我的代码 ajax.py

 #检查是从复选框的this.value(Javascript)。 
datetime = timezone.now()if checked else无

$ order_pk发送到Ajax函数。
order = Order.objects.get(pk = order_pk)
order.time = datetime
order.save()

返回simplejson.dumps({
'error':False,
'datetime':dateformat.format(datetime,'F j,Y,P')如果选中无
})

所以即使当前时间是 2012年4月14日下午5:52 在EST时间(我的当地时区),JSON响应将返回 2012年4月14日,9:52 pm ,因为那是UTC时间。



另外我注意到,Django为每个请求存储一个名为 TIME_ZONE 的模板变量(实际上不是请求的一部分变量),所以因为我是 America / New_York ,我假设Django可以计算出每个访问者自己的本地时区(基于HTTP头)?



无论如何,我的问题是双重的:


  1. 我可以在我的 ajax.py 中获取访问者的本地时区吗? (可能会像 {{TIME_ZONE}} 一样的字符串参数传递它)

  2. 使用访问者的本地时区,如何转换UTC使用Django的 dateformat
  3. $ b将timezone.now()输入到本地时区并输出为字符串$ b

编辑:为@agf



timezone.now()给出了 USE_TZ = True 的UTC时间:

 #从django.utils.timezone 
def now():

返回一个有意义的或天真的datetime.datetime,具体取决于settings.USE_TZ。

如果settings.USE_TZ:
#timeit显示datetime.now(tz = utc)慢24%
return datetime.utcnow()。replace(tzinfo = utc)
else:
return datetime.now()

是否无论如何将 datetime 转换为UTC以外的东西?例如,我可以像 current_time = timezone.now(),然后 current_time.replace(tzinfo = est)(EST =东部标准时间)?

解决方案

您需要阅读 Django Timezones文档



一个重点:


没有相当于Accept-Language HTTP标题,Django可以用来自动确定用户的时区。


你必须问用户他们的时区是什么或只是使用



您还需要确保:

  USE_TZ =您的 settings.py 中的

/ p>

一旦您有时区 tz ,您可以:

  from django.utils import timezone 

timezone.activate(tz)

datetime = timezone.now()if checked else无

获取时区感知 datetime 对象在时区 tz


I understand that the best practice now with Django 1.4 is to store all datetime in UTC and I agree with that. I also understand that all timezone conversation should be done in the template level like this:

{% load tz %}

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

However, I need to convert the UTC time to the request's local time all in Python. I can't use the template tags since I am returning the string in JSON using Ajax (more specifically Dajaxice).

Currently this is my code 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'
})

So even if the current time is April 14, 2012, 5:52 p.m. in EST time (my local timezone), the JSON response will return April 14, 2012, 9:52 p.m, because that is the UTC time.

Also I noticed that Django stores a template variable called TIME_ZONE for each request (not actually part of the request variable), so since my is America/New_York, I'm assuming that Django can figure out each visitor's own local timezone (based on HTTP header)?

Anyway, so my question is two-fold:

  1. How do I get the visitor's local timezone in my ajax.py? (Probably pass it as a string argument like {{ TIME_ZONE }})
  2. With the visitor's local timezone, how to convert the UTC timezone.now() to the local timezone and output as a string using Django's dateformat?

EDIT: for @agf

timezone.now() gives the UTC time when 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()

Is there anyway to convert a datetime to something other than UTC? For example, can I do something like current_time = timezone.now(), then current_time.replace(tzinfo=est) (EST = Eastern Standard Time)?

解决方案

You need to read the Django Timezones docs carefully.

One important point:

there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically.

You have to ask the user what their timezone is or just use a default.

You also need to make sure:

USE_TZ = True

in your settings.py.

Once you have a timezone tz, you can:

from django.utils import timezone

timezone.activate(tz)

datetime = timezone.now() if checked else None

to get a timezone-aware datetime object in timezone tz.

这篇关于如何获取访问者的当前时区,然后将timezone.now()转换为Django 1.4中本地时间的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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