2012-05-15 32 views
8

我在db中有一个字段timestamp = models.DateTimeField(auto_now_add = True)。我想找到时间戳和datetime.now()之间的区别。不能在django中减去datetime和timestamp?

当我试图datetime.now() - 时间戳,我得到的错误:

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

我该如何解决这个问题?

+0

可能重复的[不能减去偏移天真和偏移感知日期时间](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.

Django的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) 

您应该确定您是否要在您的网站时区的意识和然后相应地调整您的存储时间。要转换的认识DT幼稚,你可以使用pytz module和做到这一点:

naive_dt = aware_dt.replace(tzinfo=None) 

这工作,因为所有的Python日期时间有一个可选的时区属性,tzinfo,它可以被用来存储在DT的信息,从UTC偏移时间。

0

HOLA
简短的回答是:

tz_info = your_timezone_aware_variable.tzinfo 

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

您必须将时区信息添加到您的NOW()的时间。
但是,您必须添加相同的时区的变量,这就是为什么我第一次阅读tzinfo属性。