0

私はこれをタイムゾーンで把握するのに本当に苦労しています。私はこのようなモデルのカレンダーアプリを持っています:

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-dbには次の内容が含まれます。

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

これは私にはUTCタイムスタンプのように思えます(これは正しいと思います)。htmlをレンダリングするときは、を使用してすべて問題ありません{{event.dtstart|date:"H.i"}}。本来は19:00を表示します。ただし、問題は__unicode__、Eventクラスの-メソッドがを返すこと2013-03-04 18:00です。ご覧のとおり、これを修正しようとしましたが、行き詰まりました。私の問題はどこにあり、代わりにこの__unicode__メソッドを返すにはどうすればよいですか。2013-03-04 19:00今ここスウェーデンでは夏時間だと思います。

4

1 に答える 1

1

.replace(tzinfo=tz)タイムゾーンの設定には使用しないでくださいtz.localize()。代わりに次を使用してください。

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

See the pytz documentation:

The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):

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

However, if your datetimes are UTC times, you should use the UTC timezone instead, then express the time in a different timezone for display:

from pytz import UTC

aware = UTC.localize(timezone.get_current_timezone())
dt = aware.astimezone(timezone.get_current_timezone()).strftime('%Y-%m-%d %H:%M')
于 2013-03-03T17:31:43.967 に答える