Django DateTime字段收到了一个天真的日期时间

时间:2017-02-22 09:25:42

标签: python django datetime

我已经看过几次这个问题了,我已经按照建议的答案,但是我仍然得到错误:

/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: DateTimeField CircuitMaintenance.end_time received a naive datetime (2017-02-24 23:59:59) while time zone support is active.
  RuntimeWarning)

从我读过的django utils时区而不是datetime.now()应该解决问题,但它没有。我在settings.py

中也有以下设置
LANGUAGE_CODE = 'en-gb'

TIME_ZONE = 'Europe/London'

USE_I18N = True

USE_L10N = True

USE_TZ = True

from django.utils import timezone
dt_now = timezone.now()
days_away = datetime(dt_now.year, dt_now.month, dt_now.day) + timedelta(days)
days_away_end = days_away + timedelta(hours=23,minutes=59,seconds=59)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=days_away, end_time__lte=days_away_end,circuit__site_data__site_type="Major Site")

1 个答案:

答案 0 :(得分:2)

可能是因为创建days_away时时区信息丢失了。您只需将timezone.now()添加到timedelta

即可
days_away = timezone.now() + timedelta(days)

要将默认时间数据设置为午夜,您可以使用replace

days_away = timezone.now().replace(hour=0,minute=0, second=0) + timedelta(days)

另外,请注意您拥有的是警告,而不是错误。