Django时区感知DateTimeField默认值时区感知错误 [英] Django Timezone aware DateTimeField default value timezone awareness error

查看:174
本文介绍了Django时区感知DateTimeField默认值时区感知错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将DateTimeField添加到我的Django模型中,并将最大时间戳记作为默认值。我已经弄清楚了,Django中的最大时间戳是9999/12/31 23:59:59,与我的postgres DB中使用的最大时间戳不同。当使用此时间戳作为字段的默认值时,出现 OverflowError:日期值超出范围错误。因此,我用9999/01/01 00:00:00尝试了相同的操作:

I am trying to add a DateTimeField to my django model with the maximum timestamp as default value. I already figured out, that the maximum timestamp in Django is 9999/12/31 23:59:59 unlike the maximum timestamp used in my postgres DB. When using this timestamp as default value for the field I get an OverflowError: date value out of range error. Therefore I tried the same with 9999/01/01 00:00:00 like so:

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

现在,当我申请时这次向数据库的南迁移,我得到以下异常:

Now, when I apply this south migration to the database, I get the following exception:

RuntimeWarning:DateTimeField收到一个简单的日期时间(9999-01-01 00:00 :00),时区支持处于活动状态。

在查询数据库时,我发现本地时区已应用于默认时区。值: 9999-01-01 00:00:00 + 01 这使我得出结论,即以某种方式忽略了时区感知,但是我不知道为什么

When looking into the database, I see that my local timezone has been applied to the default value: 9999-01-01 00:00:00+01 This leads me to the conclusion, that somehow the timezone awareness is ignored by django, but I have no idea why that could be.

其他信息:

Django TIME_ZONE设置为欧洲/柏林

Django TIME_ZONE is set to 'Europe/Berlin'

USE_TZ是正确的

USE_TZ is True

我们将不胜感激。

推荐答案

尝试在日期时间instea调用 replace d将tzinfo传递到日期时间的 __ init __ 中。摘录自 django文档:

Try calling replace on the datetime instead of passing the tzinfo into the __init__ of the datetime. Taken from the django docs:

import datetime
from django.utils.timezone import utc

now = datetime.datetime(9999, 1, 1).replace(tzinfo=utc)

这篇关于Django时区感知DateTimeField默认值时区感知错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆