如何根据我的时区将正确的时间写入数据库? [英] How to write the right time to DB according my timezone?

查看:29
本文介绍了如何根据我的时区将正确的时间写入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在数据库中保存日期时,Django会在正确的时间显示有关成功添加的消息,但实际上在数据库中的时间是不同的

When I save dates in my database Django shows message about succesfull adding with the right time but in fact in the databese time is different

models.py:

models.py:

from datetime import datetime
from django.db import models


class Teg1(models.Model):
    created_at = models.DateTimeField(default=datetime.now, null=True, blank=True, editable=False)
    num = models.FloatField(default=0.0, null=True, blank=True)

    def __str__(self):
        return str(self.num) + " || " + str(self.created_at)

settings.py

settings.py

TIME_ZONE = 'Asia/Novosibirsk'
USE_TZ = True

推荐答案

Django的

The first sentence of Django's time zone documentation explains what you're seeing:

启用时区支持后,Django将日期时间信息存储在数据库中的UTC中,在内部使用可识别时区的日期时间对象,并将其以模板和形式转换为最终用户的时区.

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

因此数据库值采用UTC. str()值也位于UTC中,因为您已手动将UTC日期时间转换为字符串,而不更改时区.由于模板会将 DateTimeFields 转换为当前时区,因此由表单解释并由模板显示的值位于您的本地时间.

So the database value is in UTC. The str() value is also in UTC, since you've manually converted the UTC datetime to a string without changing the timezone. The value interpreted by the form and displayed by the template is in your local time, since templates convert DateTimeFields to the current timezone.

如果您希望 str()值使用本地时区,则可以使用Django的

If you want the str() value to use the local timezone you can use Django's localtime() function:

from django.utils.timezone import localtime

class Teg1(models.Model):
    ...

    def __str__(self):
        return str(self.num) + " || " + str(localtime(self.created_at))

这篇关于如何根据我的时区将正确的时间写入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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