python django

【小记】消除Django的RuntimeWarning:DateTimeField警告

技术分享

systemime
2021-06-22
3 min

解决warnings.warn("DateTimeField %s received a naive datetime (%s)"问题

# 一个看着很难受的警告

/python3.9/site-packages/django/db/models/fields/init.py:1416: RuntimeWarning: DateTimeField XXXXXXModel.xxx_time received a naive datetime (2021-06-30 17:00:00) while time zone support is active.

warnings.warn("DateTimeField %s received a naive datetime (%s)"

为什么会出现这个警告呢,可以追溯到2013年的提案 https://code.djangoproject.com/ticket/19560

但是很明显,我在django3.2中仍然遇到了这个问题,不知道在这8年间django是不是又把它改了回去

# 解决方案

当然,这个警告有一定道理,我们需要对准备存入 DateTimeField 字段的数据进行处理,办法就是使用django自带的 timezone 库解决

# 注:如果使用timezone,先配置django时区

from django.utils import timezone

def format_time(_datetime):
    """
    :param: :_datetime 格式 %Y-%m-%d %H:%M:%S
    """
    if _datetime:
        return timezone.get_current_timezone().localize(_datetime)
        # 或
        # timezone.make_aware(datetime.now(), timezone.get_current_timezone())
    return _datetime

# datetime与timezone数据对比

In [1]: timezone.now()
Out[1]: datetime.datetime(2021, 06, 12, 10, 14, 29, 795657, tzinfo=<UTC>)
 
In [2]: timezone.make_aware(datetime.now(), timezone.get_current_timezone())
Out[2]: datetime.datetime(2021, 06, 12, 18, 14, 31, 612764, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

In [3]: timezone.get_current_timezone().localize(datetime.now())
Out[3]: datetime.datetime(2021, 06, 12, 18, 14, 31, 612764, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

# 将字符串转化为datetime并存入数据库

>>> user = User.objects.get(id=1)
>>> date_str = "2018-03-11"

>>> from django.utils.dateparse import parse_date // Way 1
>>> temp_date = parse_date(date_str)
>>> a1 = Article(headline="String converted to date", pub_date=temp_date, reporter=user)
>>> a1.save()
>>> a1.pub_date
datetime.date(2018, 3, 11)

>>> from datetime import datetime // Way 2
>>> temp_date = datetime.strptime(date_str, "%Y-%m-%d").date()
>>> a2 = Article(headline="String converted to date way 2", pub_date=temp_date, reporter=user)
>>> a2.save()
>>> a2.pub_date
datetime.date(2018, 3, 11)
上次编辑于: 7/5/2021, 3:34:20 AM