简体   繁体   English

Django 显示的日期时间不会根据用户的本地时区而改变

[英]Django's displayed datetime doesn't change based on the user's local timezone

models.py模型.py

from django.db import models

# Create your models here.

class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Returns a string representation of the model."""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        if len(self.text) > 50:
            return f"{self.text[:50]}..."
        else:
            return self.text

template value {{ entry.date_added|date:'M d, Y g:i' }}模板值{{ entry.date_added|date:'M d, Y g:i' }}

In a template, if I display the date_added variable, it seems that the time is 8 hours behind from my computer's time.在模板中,如果我显示 date_added 变量,时间似乎比我的计算机时间晚了 8 小时。 I tried to change the timezone in settings, but I was met with ValueError: Incorrect timezone setting .我试图更改设置中的时区,但遇到了ValueError: Incorrect timezone setting

Edit: USE_TZ is set to true.编辑: USE_TZ设置为 true。

In the following template code, localtime on doesn't affect the date, strangely only displaying the server time.在下面的模板代码中, localtime on 不影响日期,奇怪的是只显示服务器时间。

            {% load tz %}

            {% timezone "Europe/Paris" %}
                <p>Paris time: {{ entry.date_added|date:'M d, Y g:i' }}</p>
            {% endtimezone %}

            {% timezone None %}
                <p>Server time: {{ entry.date_added|date:'M d, Y g:i' }}</p>
            {% endtimezone %}

            {% localtime on %}
                <p>Local Time: {{ entry.date_added|localtime }}</p>
            {% endlocaltime %}

In you settings.py file your default time zone is set to在您的 settings.py 文件中,您的默认时区设置为

TIME_ZONE = 'UTC'

You're going to want to leave this as-is so you don't encounter issues with DST.您将希望保持原样,这样您就不会遇到 DST 问题。 Once you obtain your object from the database, it will be up to you to convert to the local timezone.从数据库中获取 object 后,将由您决定转换为本地时区。 In order to get the local timezone, you can ask the user directly and save the timezone to their profile using something like pytz .为了获取本地时区,您可以直接询问用户并使用类似pytz的方式将时区保存到他们的个人资料中。

See the example from the django docs on timezones .请参阅django 文档中关于时区的示例。

If you are not concerned about showing the proper timezone for all users and just want to quickly change it for your own sake, you can set the timezone in your template.如果您不关心为所有用户显示正确的时区,而只想快速更改它,您可以在模板中设置时区。

{% load tz %}

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

{% timezone None %}
    Server time: {{ value }}
{% endtimezone %}

https://en.wikipedia.org/wiki/List_of_tz_database_time_zoneshttps://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Setting the TIME_ZONE variable in settings to the string associated with a 3 letter time zone code in the table above worked.将设置中的 TIME_ZONE 变量设置为与上表中的 3 个字母时区代码关联的字符串是可行的。

eg TIME_ZONE = 'Country/City_Name'例如TIME_ZONE = 'Country/City_Name'


EDIT : Setting the server time to UTC and then providing the user their local time converted using Javascript would work, and is probably the best method of going about this.编辑:将服务器时间设置为 UTC,然后向用户提供使用 Javascript 转换的本地时间,这可能是解决此问题的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM