我在让Django在我当地的timzeone中渲染一个日期时间字段时遇到了很多麻烦。
Settings.py包含:
TIME_ZONE = 'UTC'
USE_TZ = True
USE_L10N = True
在我的模特中,我有:
class ExportRecord(models.Model):
[...]
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
[...]
self.created = timezone.now()
Created在MySQL中存储为UTC时间对象。
如果我在填充创建的字段后在数据库中有“2016-11-08 01:25:15”,那么当我渲染模板时,我希望它被翻译成客户端的本地时间< / strong>(我在东部时间,所以我预计它会是“2016-11-07 20:25:15”。
但是,无论我使用什么标签(例如{{date_obg | localtime}}),日期都不会呈现为我当地的时间。
我安装了tzlocal,当我在视图中运行get_localzone()时,它显示'UTC'作为输出。
此外,如果我尝试这个(将我创建的字段从UTC转换为我的本地时区变量):
lctz = get_localzone()
self.created.replace(tzinfo=pytz.utc).astimezone('lctz')
>>>>2016-11-08 01:25:15
创建的日期与数据库中的日期保持一致(以UTC格式)。
这是因为我的Google App Engine实例的本地时区是UTC吗?如何让我的应用程序模板在我的用户/客户端时区中呈现?
答案 0 :(得分:0)
我的激活时区的中间件如下所示:
import pytz
from django.utils import timezone
class get_user_timezone(object):
def process_request(self, request):
if request.user.is_authenticated():
user_timezone =
pytz.timezone(request.user.userprofile.iana_timezone)
if user_timezone:
timezone.activate(user_timezone)
else:
timezone.deactivate()