【问题标题】:Django Timezone aware DateTimeField default value timezone awareness errorDjango 时区感知 DateTimeField 默认值时区感知错误
【发布时间】:2013-07-08 04:29:46
【问题描述】:

我正在尝试将 DateTimeField 添加到我的 django 模型中,并将最大时间戳作为默认值。我已经发现,Django 中的最大时间戳是 9999/12/31 23:59:59,这与我的 postgres DB 中使用的最大时间戳不同。将此时间戳用作字段的默认值时,我收到 OverflowError: date value out of range 错误。因此,我对 9999/01/01 00:00:00 进行了同样的尝试,如下所示:

start_time = models.DateTimeField(null=False, default=datetime.datetime(9999,01,01,00,00,00,tzinfo=utc))

现在,当我将此南迁移应用到数据库时,出现以下异常:

RuntimeWarning: DateTimeField received a naive datetime (9999-01-01 00:00:00) while time zone support is active.

查看数据库时,我看到我的本地时区已应用于默认值:9999-01-01 00:00:00+01 这使我得出结论,不知何故,django 忽略了时区意识,但我不知道为什么可能是。

附加信息:

Django TIME_ZONE 设置为“欧洲/柏林”

USE_TZ 为真

感谢任何帮助。

【问题讨论】:

    标签: django django-models timestamp-with-timezone


    【解决方案1】:

    尝试在日期时间调用replace,而不是将tzinfo 传递到日期时间的__init__。取自django docs:

    import datetime
    from django.utils.timezone import utc
    
    now = datetime.datetime(9999, 1, 1).replace(tzinfo=utc)
    

    【讨论】:

    • 我以为我以前尝试过,但这实际上起到了作用。谢谢。
    猜你喜欢
    • 2016-05-07
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    相关资源
    最近更新 更多