Django应用程序在使用Heroku托管时未显示本地时间

时间:2015-01-27 03:46:04

标签: django heroku time timezone datetime-format

初学者Django程序员在这里。我正在研究Django应用程序并且遇到时区问题。当我在本地服务器上运行时,我的代码成功地将时间对象转换为本地时间,但当我的应用程序在Heroku上托管时,此转换不起作用。

我目前正在使用tzlocal扩展名转换时区。在我的观点中,我使用代码:

activate(get_localzone())

在我的本地服务器上,get_localzone()成功返回本地时间。在我的应用程序的Heroku托管版本上,get_localzone()返回UTC。

以下是我在settings.py中的时间设置:

TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

不确定这是否重要但我使用的是Postgres数据库:

DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}

以下是我的主页视图示例,让您了解我如何使用tzlocal包:

def home(请求):     如果不是request.user.is_authenticated():         return render(request,'idealist / index.html')     其他:         context = RequestContext(request)         激活(get_localzone())         user = UserProfile.objects.filter(user = request.user)[0]         user_projects = user.projects()

    events = user.events()
    event_dict = SortedDict()
    string = get_localzone()

    for event in reversed(events):
        date = event.datew.astimezone(get_localzone())
        date = date.strftime("%B") + " " + str(date.day)
        if date in event_dict.keys():
            event_dict[date].append(event)
        else:
            event_dict[date] = [event]

    return render_to_response('idealist/account_home.html', {'string': string, 'user': user, 'event_dict': event_dict, 'user_projects': user_projects}, context)

此外,以下是我正在导入的其他与时间相关的包:

from django.utils.timezone import *
import pytz
from tzlocal import *
import datetime
from pytz import timezone

非常感谢你的帮助。如果我能为您提供任何其他信息,请告诉我们!

1 个答案:

答案 0 :(得分:1)

在回答一条建议之前,永远不要存储本地化的时区。始终以UTC格式存储日期,并根据需要转换应用程序。

get_localzone()可能正在占用服务器时区,你的本地时区可以使用,而heroku服务器可能设置为UTC。您有几个选择:

1)将服务器时区设置为您想要的任何内容

我不是百分百肯定这会起作用,但也许值得一试。也许将TZ变量设置为您想要的时区将使其成为当地时区。尝试使用:

heroku config:add TZ="America/Los_Angeles"

替换为您想要的timezone from this list

2)强制django使用你想要的时区

这可能是一个更好的选择,因为您不必记住再次设置时区,以防您更改提供程序或更改heroku服务器。

而不是使用get_localzone()传递您想要的时区名称,如下所示:

timezone.activate(pytz.timezone('America/Los_Angeles'))

我假设您始终希望在整个应用程序中使用相同的时区,但如果您希望允许用户选择自己的时区,则可以将该值存储在用户会话或配置文件中。 The Django docs has some good resources on this