首页 > 数据库技术 > 详细

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

时间:2019-02-16 19:21:23      阅读:223      评论:0      收藏:0      [点我收藏+]

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

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的显示格式

<QuerySet [(datetime.datetime(2019, 2, 1, 0, 0, tzinfo=<DstTzInfo Asia/Shanghai CST+8:00:00 STD>), 2)]>

设置USE_TZ为Flase的显示格式

<QuerySet [(datetime.datetime(2019, 2, 1, 0, 0), 2)]>

 

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

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

  1. 保证存储到数据库中的是 UTC 时间;
  2. 在函数之间传递时间参数时,确保时间已经转换成 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

 

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

原文:https://www.cnblogs.com/lshedward/p/10388779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!