【问题标题】:Django application not showing local time when hosted using Heroku使用 Heroku 托管时,Django 应用程序不显示当地时间
【发布时间】:2015-03-25 14:51:51
【问题描述】:

这里是初学者 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 主页(请求): 如果不是 request.user.is_authenticated(): 返回渲染(请求,'理想主义者/index.html') 别的: 上下文 = RequestContext(请求) 激活(get_localzone()) 用户 = 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

非常感谢您的帮助。如果有任何其他信息可以提供给您,请告诉我!

【问题讨论】:

    标签: django heroku time timezone datetime-format


    【解决方案1】:

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

    get_localzone() 可能正在选择服务器时区,您的时区位于您所谓的本地时区,而 heroku 服务器可能设置为 UTC。您有几个选择:

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

    我不能 100% 确定这会奏效,但也许值得一试。也许将 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.

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 2020-09-04
      • 2021-04-08
      • 2021-04-30
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多