2012-05-15 5 views
8

私はフィールドタイムスタンプ= models.DateTimeField(auto_now_add = True)をデータベースに持っています。私はそのタイムスタンプとdatetime.now()の違いを知りたい。私はこの問題を解決するにはどうすればよいdjangoでdatetimeとtimestampを減算できませんか?

can't subtract offset-naive and offset-aware datetimes 

: - 私はdatetime.now()しようとしたとき

タイムスタンプを、私はエラーを取得しますか?

+0

可能な複製[offset-naiveとoffset-aware datetimesを減算することはできません](http://stackoverflow.com/questions/796008/cant-subtract-offset-naive-and-offset-aware-datetimes) – user1023979

答えて

20

このエラーは、時刻がPythonによってどのように格納されるかを示します。パイソンdocumentationによると:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment.

ジャンゴdocumentationもと述べている:あなたは、あなたのサイトでのタイムゾーンの意識をするかどうかを決定する必要があり

When time zone support is disabled, Django uses naive datetime objects in local time. This is simple and sufficient for many use cases. In this mode, to obtain the current time, you would write:

import datetime 
now = datetime.datetime.now() 

When time zone support is enabled, Django uses time-zone-aware datetime objects. If your code creates datetime objects, they should be aware too. In this mode, the example above becomes:

import datetime 
from django.utils.timezone import utc 
now = datetime.datetime.utcnow().replace(tzinfo=utc) 

とそれに応じて保存時間を調整します。すべてのpythonの日付時刻がUTCからのオフセットのDTの情報を格納するために使用することができ、オプションのタイムゾーン属性、tzinfoを持っているので、これは動作します

naive_dt = aware_dt.replace(tzinfo=None) 

:ナイーブにdtが意識を変換するには、pytz moduleを使用してこれを行うことができます時間。

0

HOLA
短い答えは:

tz_info = your_timezone_aware_variable.tzinfo 

diff = datetime.datetime.now(tz_info) - your_timezone_aware_variable: 

あなたは今()の時間にタイムゾーン情報を追加する必要があります。
しかし、同じ変数のタイムゾーンを追加する必要があります。その理由は、最初にtzinfo属性を読み取る理由です。

関連する問題