【发布时间】: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