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

后端 未结 2 1026
野趣味
野趣味 2021-01-27 05:35

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:

2条回答
  •  礼貌的吻别
    2021-01-27 05:51

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

提交回复
热议问题