gpt4 book ai didi

python - django 不正确地将日期时间输入数据库

转载 作者:行者123 更新时间:2023-11-29 08:26:44 24 4
gpt4 key购买 nike

在我的 Django 应用程序中,我有一个 View 将数据提交到我的任务模型的数据库。这些字段之一包括时间。每当我提交该数据然后将其读回我的应用程序时,它看起来都是正确的(即我的索引页面包含所有对象的列表)。然而,当我查看数据库条目时,它们的存储时间都是在我输入后 5 小时后的。令我困惑的是它们如何可能被错误地输入以及为什么它在我的索引中正确显示。我检查了添加它的位置,如下所示。

hour = int(request.POST['time'][:2] #request.POST['time'] is formatted HH:MM AM
minute = int(request.POST['time'][3:5]
pmOffset = 0
if 'PM' in request.POST['time']:
pmOffset = 12
print task.date
task.date = datetime.now().replace(hour=hour+pmOffset, minute=minute)
print task.date
#some other fields
print task.date
task.save()
print task.date

如果我在表单中输入 07:00 AM,这些打印语句将显示上午 7 点,但存储的任务中显示中午。任何人都知道为什么会发生这种情况?我完全困惑了。如果您需要更多信息,请询问。

最佳答案

它按照设计的方式工作。默认情况下,MySQL stores the datetime objects in UTC

Values for TIMESTAMP columns are converted from the current time zone to UTC for storage, and from UTC to the current time zone for retrieval.

在你的 django 设置中,default timezone is America/Chicago比 UTC 晚 5 小时。因此结果

关于python - django 不正确地将日期时间输入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com