在我的 django 应用程序中,我将时间存储在我的数据库 (postgresql) 中。数据库中存储的时间如下所示:2015-03-23 16:02:12.163084+03。问题是,当我检索时间时,我得到的时间总是晚 3 小时。就像我上面的示例日期时间一样,检索到的时间应显示为 23 March 2015 01:02:12 PM。注意时差。我该怎么做才能确保根据用户的时区显示时间?
最佳答案
Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. Installing pytz is highly recommended, but may not be mandatory depending on your particular database backend, operating system and time zone. If you encounter an exception querying dates or times, please try installing it before filing a bug. It’s as simple as:
在settings.py
USE_TZ = True
然后
sudo pip install pytz
When support for time zones is enabled, Django stores date and time information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.
更多https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/
您可以使用模板测试差异
{% load tz %}
{% localtime on %}
{{ value }}
{% endlocaltime %}
{% localtime off %}
{{ value }}
{% endlocaltime %}
时区 FAQ会帮助你
关于python - Django 在本地时区获取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211141/