Database returned an invalid datetime value. Are time zone definitions for your database installed?

在做文章归档的会后,打印结果时报了这个错误

ret = models.Article.objects.filter(user=user).annotate(month=TruncMonth(‘created_time’)).values(‘month’).annotate(
count=Count(‘nid’)).values_list(
‘month’, ‘count’)
print(r’------>’, ret)
原因是时区问题

解决方案
在mysql设置时区

mysql> SELECT @@global.time_zone, @@session.time_zone;
±-------------------±--------------------+
| @@global.time_zone | @@session.time_zone |
±-------------------±--------------------+
| SYSTEM | SYSTEM |
±-------------------±--------------------+

修改django project下的settings.py中市区配置信息:

#USE_TZ = True

TIME_ZONE = ‘UTC’

USE_TZ = False
TIME_ZONE = ‘Asia/Shanghai’

USE_TZ是统一全球的时间,不夸时区的应用可以把这个设置为False

设置USE_TZ为True的显示格式

), 2)]>
设置USE_TZ为Flase的显示格式

参考:https://www.cnblogs.com/yy3b2007com/p/7601940.html#autoid-0-1-0

USE_TZ = True会自动转成UTC时间,用mysql的时候要注意这个问题。

启用 USE_TZ = True 后,处理时间方面,有两条 “黄金法则”:

保证存储到数据库中的是 UTC 时间;
在函数之间传递时间参数时,确保时间已经转换成 UTC 时间;
比如,通常获取当前时间用的是:

import datetime
now = datetime.datetime.now()
启用 USE_TZ = True 后,需要写成:

import datetime
from django.utils.timezone import utc
utcnow = datetime.datetime.utcnow().replace(tzinfo=utc)
模板

除非应用支持用户设置自己所在的时区,通常我们不需要关心模板的时区问题。模板在展示时间的时候,会使用 settings.TIME_ZONE 中的设置自动把 UTC 时间转成 settings.TIME_ZONE 所在时区的时间渲染。

TIME_ZONE = ‘Asia/Shanghai’

转载于:https://www.cnblogs.com/lshedward/p/10388779.html