python - Django 在本地时区获取时间

标签 python django postgresql datatables

在我的 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/

相关文章:

python - 将外键选择限制为 ManyToMany 字段选择

python - Django:缺少属性 COOKIES 的类 View

node.js - 如果postgresql中不存在如何删除

Python multiprocess.Pool.map 不能处理大数组。

python - 使 pandas 中的行操作更快

c++ - Python 和 C++ 的两种方式通信

python - 如何在 Django 中渲染缓存的 JSONP View

python - 我的 python 多处理程序按顺序运行工作程序

postgresql - postgresql 中 case 语句的总和返回 false

postgresql - 无法使用 Sequelize 的 Docker Compose 连接到 Postgres 容器