简体   繁体   English

如何在 Django 中将 UTC 时间转换为用户的本地时间?

[英]How Do I Convert UTC Time To User's Local Time in Django?

These answers didn't help:这些答案没有帮助:

  1. Getting correct local time zone to display for end-users in Django web app 获取正确的本地时区以在 Django Web 应用程序中为最终用户显示

  2. Django different timezones in same application 同一应用程序中的Django不同时区

All datetime data is stored in UTC in my database.所有日期时间数据都以 UTC 格式存储在我的数据库中。

I would like each of my users to see the datetime in their local timezone instead of UTC.我希望我的每个用户都能看到他们本地时区的日期时间,而不是 UTC。 I've tried the code below:我试过下面的代码:

settings.py设置.py

TIME_ZONE = 'UTC'

USE_TZ = True

views.py视图.py

from django.shortcuts import render
from home_app import models
from django.utils import timezone
import pytz

def home_view(request):
    timezone.activate(pytz.timezone('Asia/Kolkata'))
    sample_queryset = models.TimeModel.objects.all()
    return render(request, 'home/home.html', {'sample_queryset': sample_queryset,})

home.html主页.html

{% for row in sample_queryset %}
    {% load tz %}
    {% localtime on %}
    {{ row.time }}
    {% endlocaltime %}
{% endfor %}

models.py模型.py

from django.db import models

class TimeModel(models.Model):
    sample_text = models.CharField(max_length=255)
    time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.time) + ' ' + self.sample_text

However, after all, the same UTC time from the database is being printed.但是,毕竟正在打印来自数据库的相同 UTC 时间。

Other details:其他详情:

Django 1.11 Django 1.11

SQLite (for now; will use Postgres in production) SQLite(目前;将在生产中使用 Postgres)

Python 3.6.8蟒蛇 3.6.8

Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems.有效的时区值基于 Linux 和其他 Unix 系统使用的 tz(时区)数据库。 The values are strings (xsd:string) in the form “ Area/Location ,” in which:这些值是“区域/位置”形式的字符串 (xsd:string),其中:

Area is a continent or ocean name.区域是大陆或海洋的名称。 Area currently includes:区域目前包括:

  • Africa非洲
  • America (both North America and South America)美国(北美和南美)
  • Antarctica南极洲
  • Arctic北极
  • Asia亚洲
  • Atlantic大西洋
  • Australia澳大利亚
  • Europe欧洲
  • Etc (administrative zone. For example, “Etc/UTC” represents Coordinated Universal Time.) Etc(管理区域。例如,“Etc/UTC”代表协调世界时。)
  • Indian印度人
  • Pacific太平洋

Location is the city, island, or other regional name.位置是城市、岛屿或其他区域名称。

The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected.区域名称和输出缩写遵循 POSIX(便携式操作系统接口)UNIX 约定,它使用格林威治以西的正 (+) 号和格林威治以东的负 (-) 号,这与通常预期的相反。 For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).例如,“Etc/GMT+4”对应于 UTC 后 4 小时(即格林威治以西),而不是 UTC(协调世界时)(格林威治以东)提前 4 小时。

Here is a list all valid timezones这是所有有效时区的列表

You can change time zone in your settings.py as follows您可以在 settings.py 中更改时区,如下所示

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

The issue looks in your template code, it should be something like问题出现在您的模板代码中,它应该类似于

{% for row in sample_queryset %}
    {% load tz %}
    {% timezone timezone_string %}
    {{ row.time }}
    {% endtimezone %}

{% endfor %}

I suspect as per here localtime the timezone getting picked up for you is UTC from settings.py You should use this instead timezone我怀疑根据这里本地时间为您获取的时区是来自 settings.py 的 UTC 您应该使用它而不是时区

I have migrated to Postgres from SQLite and made the following changes:我已经从 SQLite 迁移到 Postgres 并进行了以下更改:

models.py模型.py

Before:前:

from django.db import models从 django.db 导入模型

class TimeModel(models.Model):
    sample_text = models.CharField(max_length=255)
    time = models.DateTimeField(auto_now=True) # changed time to dt

    def __str__(self):
        return str(self.time) + ' ' + self.sample_text

After:后:

from django.db import models

class TimeModel(models.Model):
    sample_text = models.CharField(max_length=255)
    dt = models.DateTimeField(auto_now=True) # changed time to dt

    def __str__(self):
        return str(self.dt) + ' ' + self.sample_text

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

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