2

我一直在处理 django 中的一个小问题,但我还没有完全弄清楚。我有一个在 godaddy vps 上运行的 django 应用程序,在 views.py 中我将这些行作为函数定义的一部分

    currtime=datetime.datetime.now()
            return render_to_response('test.html',{'currtime' : currtime })

现在在我的 test.html 中,我使用模板来获取当前时间

          {% load tz %}
          {% localtime on %} 
          <p>{{currtime}}</p>
          {% endlocaltime %}

我相信 django 中的时区感知 datetime 对象的要点是在通过模板呈现 HTML 时自动将时间转换为本地时间。如您在上面看到的,我已经加载了 pytz 库并启用了本地时间......即使我我在印度我仍然得到一个当前时间值,它与德克萨斯州 CDT 中的时间相同。我希望它工作的原因是,我有一个日期时间存储在 UTC 的数据库,我希望根据用户的地理位置以本地时间显示时间(即从 UTC 转换为本地时间)。任何帮助将不胜感激,谢谢。

4

1 回答 1

0

I just got here accidentally googling for a related problem, but I thought I'd answer, just in case someone finds it as well...

What you were after didn't work, because localtime means the local time on the server (expressed in the timezone as defined in your settings). The django app running on the server has no way of figuring out what the client's timezone is. You should detect the timezone in the browser, e.g. using jstz.

A more robust solution is to let the users choose their own timezone, but also setting the selection using autodetection (so that most of the time they can just press OK). Then of course you can store this on the server and from that point on, you can generate your templates using the user's timezone:

{% loadtz %}
{% timezone user.timezone %}
.....
{% endtimezone %}
于 2015-04-30T23:36:19.277 回答