2012-05-15 36 views
8

Tôi có một dấu thời gian trường = models.DateTimeField (auto_now_add = True) trong db. Tôi muốn tìm sự khác biệt giữa dấu thời gian đó và datetime.now().Không thể trừ datetime và dấu thời gian trong django?

Khi tôi cố gắng datetime.now() - dấu thời gian, tôi nhận được thông báo lỗi:

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

Làm thế nào để sửa lỗi này?

+0

bản sao có thể có của [Không thể trừ các khoảng thời gian bù đắp bù trừ-ngây thơ và bù trừ] (http://stackoverflow.com/questions/796008/cant-subtract-offset-naive-and-offset-aware-datetimes) – user1023979

Trả lời

20

Lỗi này đề cập đến thời gian được lưu trữ bởi python. Theo 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.

Các django documentation cũng khẳng định rằng:

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) 

Bạn nên xác định có hay không bạn muốn nhận thức múi giờ trong trang web của bạn và sau đó điều chỉnh thời gian lưu trữ của bạn cho phù hợp. Để chuyển đổi một ý thức dt để ngây thơ bạn có thể sử dụng pytz module và làm điều này:

naive_dt = aware_dt.replace(tzinfo=None) 

này hoạt động bởi vì tất cả datetimes python có một thuộc tính múi giờ tùy chọn, tzinfo, có thể được sử dụng để lưu trữ thông tin trên dt của bù đắp từ UTC thời gian.

0

Hola
Câu trả lời ngắn gọn là:

tz_info = your_timezone_aware_variable.tzinfo 

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

Bạn phải thêm các thông tin múi giờ để thời gian bây giờ() của bạn.
Nhưng bạn phải thêm cùng một múi giờ của biến, đó là lý do tại sao tôi lần đầu tiên đọc thuộc tính tzinfo.

Các vấn đề liên quan