2012-05-15 11 views
8

Ho un campo timestamp = models.DateTimeField (auto_now_add = True) nel db. Voglio trovare la differenza tra quel timestamp e datetime.now().Non è possibile sottrarre datetime e timestamp in django?

Quando ho provato datetime.now() - timestamp, ottengo l'errore:

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

Come posso risolvere questo problema?

+0

possibile duplicato di [Impossibile sottrarre datazioni offset-naive e offset-aware] (http://stackoverflow.com/questions/796008/cant-subtract-offset-naive-and-offset-aware-datetimes) – user1023979

risposta

20

Questo errore si riferisce a come i tempi vengono memorizzati da python. Secondo il pitone 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.

il Django documentation afferma anche che:

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) 

Si dovrebbe determinare se si desidera o meno la consapevolezza fuso orario nel vostro sito e quindi regolare i tempi memorizzati di conseguenza. Per convertire un consapevole dt per ingenuo è possibile utilizzare il pytz module e fare questo:

naive_dt = aware_dt.replace(tzinfo=None) 

Questo funziona perché tutti datetimes pitone hanno un attributo fuso orario facoltativo, tzinfo, che può essere utilizzato per memorizzare le informazioni sul dt del compensato da UTC tempo.

0

Holá
La risposta breve è:

tz_info = your_timezone_aware_variable.tzinfo 

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

È necessario aggiungere le informazioni fuso orario per il vostro tempo ora().
Ma è necessario aggiungere lo stesso fuso orario della variabile , ecco perché ho letto l'attributo tzinfo.