How to write the right time to DB according my timezone?

ε祈祈猫儿з 提交于 2021-02-05 09:44:58

问题


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:

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

TIME_ZONE = 'Asia/Novosibirsk'
USE_TZ = True

回答1:


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

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.

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.

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))



回答2:


If i'm not mistaken, you must be in Russia which is 7 hours ahead of UTC. So, the server that you use must be using the UTC time which in my opinion is a good thing.
I personally prefer to save times in UTC time in the data base and then convert them to the local time in the front end.

from django.utils import timezone
from datetime import datetime

teg1 = Teg1(created_at=datetime.now(tz=timezone.utc)
teg1.save()

However, if you want to save the datetime in your local time, you can use:

from datetime import datetime    
import pytz

novosibirsk = pytz.timezone("Asia/Novosibirsk")
now = datetime.now(novosibirsk)
teg1 = Teg1(created_at=now)
teg1.save()

Have in mind that in your admin interface, you might see the time and date based on the timezone you select in your settings.py. However, the data saved in the database is still in UTC time.



来源:https://stackoverflow.com/questions/52852083/how-to-write-the-right-time-to-db-according-my-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!