不能让时区datetime对象打印正确的时间

问题描述:

我真的很难把握这与时区。我有一个日历应用程序,像这样一个模型:不能让时区datetime对象打印正确的时间

class Events(models.Model): 
    dtstart = models.DateTimeField('Start') 
    ... 

    def __unicode__(self): 
     aware = self.dtstart.replace(tzinfo=timezone.get_current_timezone()) 
     #dt = defaultfilters.date(aware, 'Y-m-d H') 
     dt = aware.strftime('%Y-%m-%d %H:%M') 
     return dt 

和settings.py包含此:

TIME_ZONE = 'Europe/Stockholm' 
USE_TZ = True 

如果我使用Django管理界面添加的事件开始约19:00明天,sqlite数据库将包含此:

$ sqlite3 ~/django_test.db "SELECT dtstart from events_events" 
2013-03-04 18:00:00 

这似乎是一个utc时间戳给我(我怀疑这是正确的)。当我使用{{event.dtstart|date:"H.i"}}呈现html时,这一切都很好。它应该显示19:00。但问题在于Event类的__unicode__ - 方法返回2013-03-04 18:00。我有,正如你所见,试图解决这个问题,但我卡住了。我的问题在哪里?如何使此__unicode__方法返回2013-03-04 19:00。我认为现在是瑞典的夏令时。

不要使用.replace(tzinfo=tz)设置时区,使用tz.localize()代替:

aware = timezone.get_current_timezone().localize(self.dtstart) 

pytz documentation

第一种方法是使用由pytz库提供的局部化()方法。这是用来定位一个天真的日期时间(日期时间,没有时区信息):

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0)) 
>>> print(loc_dt.strftime(fmt)) 
2002-10-27 06:00:00 EST-0500 

但是,如果你的日期时间为UTC时间,你应该使用UTC时区,而不是,然后表达的时间在不同的时区用于显示:

from pytz import UTC 

aware = UTC.localize(timezone.get_current_timezone()) 
dt = aware.astimezone(timezone.get_current_timezone()).strftime('%Y-%m-%d %H:%M')