我有一个 Django (v1.10.6) 项目,它有一些带有日期时间字段的模型,例如:
created_at = models.DateTimeField(auto_now_add=True)
存储在没有时区信息的 PostgreSQL 数据库中:
created_at timestamp without time zone NOT NULL
postgresql.conf
:timezone = 'UTC'
我希望我的申请的所有日期都显示在
America/Bogota
中时区(它不应该取决于用户的实际时区),所以我的 settings.py
文件有如下配置:TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True
SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'
但是当我写
{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}
在模板中,它仍然在
UTC
中显示日期格式。更新:
我添加了以下中间件,但没有帮助:
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
timezone.activate(pytz.timezone(settings.TIME_ZONE))
更新 2:
它的工作方式如下:
import pytz
from django.utils import timezone
timezone.is_naive(object.created_at) # True
object.created_at.replace(tzinfo=timezone.utc)
(强制日期在
UTC
时区,然后在没有 localize
过滤器的情况下将其传递给模板)但我不明白为什么 Django 在 USE_TZ
时仍然返回朴素的日期时间设置为 True
.
最佳答案
您需要选择当前时区。
You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used.
以下文档中的一些相关摘录。
The default time zone is the time zone defined by the TIME_ZONE setting.
The current time zone is the time zone that’s used for rendering.
You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used.
发件人:https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#default-time-zone-and-current-time-zone
我建议拥有所有
datetime
的内部存储在 UTC 因此设置 TIME_ZONE = 'UTC'
在您的 settings.py
然后将当前时区切换到您希望输出所在的时区。这将使您以后添加更多时区变得更加容易,并使任何日期或时间算术变得更加容易,尤其是如果您必须考虑任何夏令时更改.如果您真的不需要它,那么完全禁用时区可能会更容易。
关于django - 如何在特定时区的 Django 中显示日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144160/