最新消息:

django错误一则untimeWarning: DateTimeField received a naive datetime

Django admin 6212浏览 0评论

发生此错误的情况

我想查询一个对象的集合的日期字段是7天之前
原来是这么写的

last_expired_datetime = datetime.datetime.now() - datetime.timedelta(settings.ACCOUNT_ACTIVATION_DAYS)
 
expired_users = User.objects.filter(Q(date_joined__lt=last_expired_datetime),
            Q(is_active=False))

运行测试的时候就会发出一个警告

...../Users/vincent/.virtualenvs/dj15/lib/python2.7/site-packages/django/db/models/fields/__init__.py:827: RuntimeWarning: DateTimeField received a naive datetime (2013-04-13 02:12:21.853095) while time zone support is active.
  RuntimeWarning)

意思就是我在model里的操作日期字段的时候使用了本地时间,而不是一个UTC时间.

# 激活日期范围之前的datetime
修改如下

        last_expired_datetime = datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(settings.ACCOUNT_ACTIVATION_DAYS)
        #print last_expired_datetime
        # 查询截止到目前 超过制定日期没有激活的用户
        expired_users = User.objects.filter(Q(date_joined__lt=last_expired_datetime),
            Q(is_active=False))

警告解除

参考链接

  • https://groups.google.com/forum/?fromgroups=#!topic/django-users/HTUJUIAkL1U
  • http://stackoverflow.com/questions/10034823/django-converting-old-datetime-field-to-new-1-4-datetime-with-time-zone-aware-in
  • https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/#code

转载请注明:爱开源 » django错误一则untimeWarning: DateTimeField received a naive datetime

您必须 登录 才能发表评论!