zoukankan      html  css  js  c++  java
  • 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的显示格式

    <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会自动转成UTC时间,用mysql的时候要注意这个问题。

    启用 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'

  • 相关阅读:
    centos 下PATH变量配置错误补救办法 Alex
    基于php模块方式安装LAMP和常见LAMP应用 Alex
    php配置 Alex
    php测试小代码 Alex
    PHP简介 Alex
    2.7.JavaScriptnull与undefined
    2.9.JavaScript内置对象
    2.8.JavaScript不同数据类型转换
    2.2.javascript变量作用域
    2.6.Javascript数值型
  • 原文地址:https://www.cnblogs.com/lshedward/p/10388779.html
Copyright © 2011-2022 走看看