日期范围和天真的日期时间抛出运行警告

时间:2013-01-13 19:46:22

标签: python django

鉴于今天在Django中过滤条目的日期范围:

today_min = datetime.datetime.combine(timezone.now(), datetime.time.min)
today_max = datetime.datetime.combine(timezone.now(), datetime.time.max)
today_events = Entry.objects.filter(due_date_time__range=(today_min, today_max))

我明显使用timezone.now()代替datetime.date.today(),以便考虑时区支持,但仍然收到错误消息:

RuntimeWarning: DateTimeField received a naive datetime (2013-01-13 00:00:00) while time zone support is active.

RuntimeWarning: DateTimeField received a naive datetime (2013-01-13 23:59:59.999999) while time zone support is active.

我在俯瞰什么?感谢

1 个答案:

答案 0 :(得分:0)

根据Python 3.2中datetime模块的来源,datetime.datetime.combine的结果是这样构造的:

@classmethod
def combine(cls, date, time):
    ...

    return cls(date.year, date.month, date.day,
               time.hour, time.minute, time.second, time.microsecond,
               time.tzinfo)

所以tzinfo在这里没有被尊重,你使用combine函数的方式(如果日期时间的Python 2.X版本按照3.2版本的方式进行)。

要获取本地化的日期时间对象,Django docs建议:

from django.utils import timezone
timezone.localtime(timezone.now())