python 具有系统时区设置的 Django 与用户的个人时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1061911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:23:19  来源:igfitidea点击:

Django with system timezone setting vs user's individual timezones

pythondjangotimezone

提问by Nick Sonneveld

How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like thisscares me which is why I prefer UTC everywhere.

Django 为每个用户处理不同时区的情况如何?理想情况下,我想在 UTC 时区中运行服务器(例如,在 settings.py 中设置 TIME_ZONE="UTC"),以便所有日期时间都作为 UTC 存储在数据库中。像这样的东西让我害怕,这就是为什么我在任何地方都喜欢 UTC。

But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?

但是为每个用户存储一个时区并仍然使用标准的 django 日期时间格式和 modelform 包装器会有多困难。我是否预计必须到处编写日期处理代码才能将日期转换为用户的时区并再次转换回 UTC?

I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.

我仍在阅读 django 教程,但我知道在其他一些假设系统时区无处不在的框架中处理用户时区是多么痛苦,所以我想我现在会问。

My research at the moment consisted of searching the django documentation and only finding one referenceto timezones.

我目前的研究包括搜索 django 文档并只找到一个对时区的引用



Additional:

额外的:

采纳答案by Brian Neal

Update, January 2013: Django 1.4 now has time zone support!!

2013 年 1 月更新:Django 1.4 现在支持时区!!



Old answer for historical reasons:

由于历史原因,旧答案:

I'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom Tredinnick's advice in this django-user's post. You'll want to store the user's timezone setting in their user profile, probably.

我将自己为我的应用程序解决这个问题。我对这个问题的第一种方法是采用 django 核心开发人员 Malcom Tredinnick 在这篇 django-user's post 中的建议。您可能希望将用户的时区设置存储在他们的用户配置文件中。

I would also highly encourage you to look into the pytz module, which makes working with timezones less painful. For the front end, I created a "timezone picker" based on the common timezones in pytz. I have one select box for the area, and another for the location (e.g. US/Central is rendered with two select boxes). It makes picking timezones slightly more convenient than wading through a list of 400+ choices.

我还强烈建议您查看pytz 模块,它可以减少使用时区的痛苦。对于前端,我基于 pytz 中的常见时区创建了一个“时区选择器”。我有一个用于该区域的选择框,另一个用于该位置(例如,美国/中部用两个选择框呈现)。与浏览 400 多个选择列表相比,它使选择时区稍微方便一些。

回答by paluh

It's not that hard to write timezone aware code in django:

在 Django 中编写时区感知代码并不难:

I've written simple django application which helps handle timezones issue in django projects: https://github.com/paluh/django-tz. It's based on Brosner (django-timezone) code but takes different approach to solve the problem - I think it implements something similar to yours and FernandoEscher propositions.

我编写了简单的 django 应用程序,它有助于处理 django 项目中的时区问题:https: //github.com/paluh/django-tz。它基于 Brosner (django-timezone) 代码,但采用不同的方法来解决问题——我认为它实现了类似于你和 FernandoEscher 命题的东西。

All datetime values are stored in data base in one timezone (according to TIME_ZONE setting) and conversion to appropriate value (i.e. user timezone) are done in templates and forms (there is form widget for datetimes fields which contains additional subwidget with timezone). Every datetime conversion is explicit - no magic.

所有日期时间值都存储在一个时区的数据库中(根据 TIME_ZONE 设置),并在模板和表单中完成转换为适当的值(即用户时区)(日期时间字段的表单小部件包含带时区的附加子小部件)。每个日期时间转换都是明确的 - 没有魔法。

Additionally there is per thread cache which allows you simplify these datatime conversions (implementation is based on django i18n translation machinery).

此外,每个线程缓存允许您简化这些数据时间转换(实现基于 django i18n 翻译机制)。

When you want to remember user timezone, you should add timezone field to profile model and write simple middleware (follow the example from doc).

当您想记住用户时区时,您应该将时区字段添加到配置文件模型并编写简单的中间件(按照文档中的示例)。

回答by Jonathan Berger

Django doesn't handle it at all, largely because Python doesn't either. Python (Guido?) has so far decided not to support timezones since although a reality of the world are "more political than rational, and there is no standard suitable for every application."

Django 根本不处理它,主要是因为 Python 也不处理。Python(Guido?)到目前为止决定不支持时区,因为尽管世界的现实“更多的是而不是理性,并且没有适合每个应用程序的标准”。

The best solution for most is to not worry about it initially and rely on what Django provides by default in the settings.py file TIME_ZONE = 'America/Los_Angeles'to help later on.

对于大多数人来说,最好的解决方案是一开始不要担心它,并依靠 Django 在 settings.py 文件中默认提供的内容TIME_ZONE = 'America/Los_Angeles'来提供帮助。

Given your situation pytzis the way to go (it's already been mentioned). You can install it with easy_install. I recommend converting times on the server to UTC on the fly when they are asked for by the client, and then converting these UTC times to the user's local timezone on the client (via Javascript in the browser or via the OS with iOS/Android).

鉴于您的情况pytz是要走的路(已经提到过)。您可以使用easy_install. 我建议在客户端要求时将服务器上的时间即时转换为 UTC,然后将这些 UTC 时间转换为客户端上用户的本地时区(通过浏览器中的 Javascript 或通过 iOS/Android 操作系统) .

The server code to convert times stored in the database with the America/Los_Angelestimezone to UTC looks like this:

将数据库中存储的America/Los_Angeles时区时间转换为 UTC的服务器代码如下所示:

>>> # Get a datetime from the database somehow and store into "x"
>>> x = ...
>>>
>>> # Create an instance of the Los_Angeles timezone
>>> la_tz = pytz.timezone(settings.TIME_ZONE)
>>>
>>> # Attach timezone information to the datetime from the database
>>> x_localized = la_tz.localize(x)
>>>
>>> # Finally, convert the localized time to UTC
>>> x_utc = x_localized.astimezone(pytz.utc)

If you send x_utcdown to a web page, Javascript can convert it to the user's operating system timezone. If you send x_utcdown to an iPhone, iOS can do the same thing, etc. I hope that helps.

如果您发送x_utc到网页,Javascript 可以将其转换为用户的操作系统时区。如果你发送x_utc到 iPhone,iOS 可以做同样的事情,等等。我希望这会有所帮助。

回答by Lennart Regebro

Not a Django expert here, but afaik Django has no magic, and I can't even imagine any such magic that would work.

不是这里的 Django 专家,但 afaik Django 没有魔法,我什至无法想象任何这样的魔法会起作用。

For example: you don't always want to save times in UTC. In a calendar application, for example, you want to save the datetime in the local time that the calendar event happens. Which can be different both from the servers and the users time zone. So having code that automatically converts every selected datetime to the servers time zone would be a Very Bad Thing.

例如:您并不总是想以 UTC 格式保存时间。例如,在日历应用程序中,您希望以日历事件发生的本地时间保存日期时间。这可能与服务器和用户时区不同。因此,拥有自动将每个选定日期时间转换为服务器时区的代码将是一件非常糟糕的事情。

So yes, you will have to handle this yourself. I'd recommend to store the time zone for everything, and of course run the server in UTC, and let all the datetimes generated by the application use UTC, and then convert them to the users time zone when displaying. It's not difficult, just annoying to remember. when it comes to datetimes that are inputted by the user, it's dependant on the application if you should convert to UTC or not. I would as a general recommendation not convert to UTC but save in the users time zone, with the information of which time zone that is.

所以是的,你必须自己处理这个。我建议为所有内容存储时区,当然以 UTC 运行服务器,并让应用程序生成的所有日期时间都使用 UTC,然后在显示时将它们转换为用户时区。这并不难,只是记起来很烦人。当涉及到用户输入的日期时间时,是否应该转换为 UTC 取决于应用程序。作为一般建议,我不会转换为 UTC,而是保存在用户时区中,并包含该时区的信息。

Yes, time zones is a big problem. I've written a couple of blog posts on the annoying issue, like here: http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/

是的,时区是一个大问题。我写了几篇关于这个烦人的问题的博客文章,比如这里:http: //regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/

In the end you will have to take care of time zone issues yourself, because there is no real correct answer to most of the issues.

最后,您将不得不自己处理时区问题,因为大多数问题都没有真正正确的答案。

回答by FernandoEscher

Looking at the django-timezonesapplication I found that it doesn't support MySQL DBMS, since MySQL doesn't store any timezone reference within datetimes.

查看django-timezones应用程序,我发现它不支持 MySQL DBMS,因为 MySQL 在日期时间中不存储任何时区引用。

Well, I think I manage to work around this by forking the Brosner libraryand modifying it to work transparently within your models.

好吧,我想我设法通过分叉Brosner 库并修改它以在您的模型中透明地工作来解决这个问题。

There, I'm doing the same thing the django translation system do, so you can get user unique timezone conversion. There you should find a Field class and some datetime utils to always get datetimes converted to the user timezone. So everytime you make a request and do a query, everything will be timezoned.

在那里,我正在做与 django 翻译系统相同的事情,因此您可以获得用户唯一的时区转换。在那里,您应该找到一个 Field 类和一些日期时间实用程序,以始终将日期时间转换为用户时区。因此,每次您发出请求并进行查询时,所有内容都将进行时区划分。

Give it a try!

试一试!

回答by ayaz

You could start by taking a look at the django-timezonesapplication. It makes available a number of timezone-based model fields (and their corresponding form fields, and some decorators), which you could use to at least storedifferent timezone values per user (if nothing else).

您可以首先查看django-timezones应用程序。它提供了许多基于时区的模型字段(及其相应的表单字段和一些装饰器),您可以使用它们至少为每个用户存储不同的时区值(如果没有别的)。