Python 在 Django 中获取本地时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14657173/
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
Get local timezone in django
提问by David542
I have a mysql DATETIMEvalue that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:
我有一个DATETIME存储在系统时间 UTC 中的 mysql值。我需要将其转换为我在 Django 中的本地时区。这是我目前拥有的:
# value in mysql
`timestamp`
2013-02-01 22:48:45
# settings.py
TIME_ZONE = 'America/Los_Angeles'
# views.py
last_updated = PathLastUpdated.objects.all()[0].timestamp
print last_updated
2013-02-01 22:48:45 <-- same as UTC
How would I get the last_updated value to be in my local timezone = "America/Los Angeles" ?
我如何将 last_updated 值设为本地时区 = "America/Los Angeles" ?
采纳答案by Austin Phillips
The Django documentation for timezonesdocuments all the necessary details for converting datetimeobjects to the appropriate time zone for display.
在Django的文档时区的文件全部转换用的必要细节datetime的对象适当的时区显示。
Your data is stored in UTC which is good. When you obtain a DateTimefield object from the database it will be a naive datetime.datetimeobject. ie A date/time without a timezone attached. It's then up to you to do the conversion.
您的数据以 UTC 格式存储,这很好。当您DateTime从数据库中获取字段对象时,它将是一个简单的datetime.datetime对象。即没有附加时区的日期/时间。然后由您来进行转换。
User of your webapp may be in different time zones so the conversion to an appropriate time zone must occur for each request. This is why there is an activatefunction to set the current time zone.
您的 web 应用程序的用户可能处于不同的时区,因此必须为每个请求转换为适当的时区。这就是为什么有一个激活功能来设置当前时区。
If you have pytzinstalled you should be able to do the following:
如果您安装了pytz,您应该能够执行以下操作:
from django.utils.timezone import activate
activate(settings.TIME_ZONE)
All output of date field in the template engine will then automatically convert you naive date time objects to the correct time zone for display.
然后模板引擎中日期字段的所有输出将自动将您的原始日期时间对象转换为正确的时区以进行显示。
If you just have a single naive datetime.datetimeinstance that you want to set the time zone on, then just use the pytzmodule directly. It is not normal to do this in your views though, as it's a good idea to only convert the time zone at the point of presentation.
如果您只有一个datetime.datetime想要设置时区的简单实例,那么只需pytz直接使用该模块。但是,在您的视图中执行此操作是不正常的,因为仅在演示时转换时区是一个好主意。
from pytz import timezone
settings_time_zone = timezone(settings.TIME_ZONE)
last_updated = last_updated.astimezone(settings_time_zone)
回答by Torsten Engelbrecht
I personally would advice against using a TIME_ZONEsetting other than UTC. I remember having problems with this in the past, be it that the database was operating in a different timezone (saving values in a different timezone) than the Django backend was using. That meant a lot of hassle to compare the times, changing them forth and back depending on what you are doing.
我个人建议不要使用TIME_ZONEUTC 以外的设置。我记得过去遇到过这个问题,因为数据库在与 Django 后端使用的时区不同(在不同的时区保存值)。这意味着要比较时间会很麻烦,根据您正在做的事情来回改变它们。
A good practice is usually to use one timezone in the backend (lets say UTC) and convert the time in the frontend to the users timezone you are serving.
一个好的做法通常是在后端使用一个时区(比如 UTC)并将前端中的时间转换为您所服务的用户时区。
回答by Rich Jones
I've created a simple middleware to handle all of this stuff for you:
我创建了一个简单的中间件来为您处理所有这些事情:
https://github.com/Miserlou/django-easy-timezones
https://github.com/Miserlou/django-easy-timezones
Simply install it and follow the instructions and you're done!
只需安装它并按照说明操作即可完成!
Install django-easy-timezones
pip install django-easy-timezones pytz pygeoipAdd "easy-timezones" to your INSTALLED_APPS setting like this:
INSTALLED_APPS = ( ... 'easy-timezones', )Add EasyTimezoneMiddleware to your MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = ( ... 'easy-timezones.middleware.EasyTimezoneMiddleware', )Add a path to the MaxMind GeoIP databasein your settings file:
GEOIP_DATABASE = '/path/to/your/geoip/database/GeoIP.dat'Enable localtime in your templates.
{% load tz %} The UTC time is {{ object.date }} {% localtime on %} The local time is {{ object.date }} {% endlocaltime %}Tada!
安装 django-easy-timezones
pip install django-easy-timezones pytz pygeoip将“easy-timezones”添加到您的 INSTALLED_APPS 设置中,如下所示:
INSTALLED_APPS = ( ... 'easy-timezones', )将 EasyTimezoneMiddleware 添加到 MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = ( ... 'easy-timezones.middleware.EasyTimezoneMiddleware', )在您的设置文件中添加MaxMind GeoIP 数据库的路径:
GEOIP_DATABASE = '/path/to/your/geoip/database/GeoIP.dat'在您的模板中启用本地时间。
{% load tz %} The UTC time is {{ object.date }} {% localtime on %} The local time is {{ object.date }} {% endlocaltime %}多田!
回答by Fabio Montefuscolo
After cry a lot, I could show the correct date for my country doing something like this:
哭了很多之后,我可以显示我的国家的正确日期做这样的事情:
>>> from django.utils.timezone import get_current_timezone
>>> from front.models import Training
>>> tz = get_current_timezone()
>>> stored_date = Training.objects.first().start_date
datetime.datetime(2015, 4, 25, 17, 0, tzinfo=<UTC>)
>>> desired_date = stored_date + tz.utcoffset(stored_date)
datetime.datetime(2015, 4, 25, 14, 0, tzinfo=<UTC>)
The tzinfoattribute is shows utc, but the date and time is correct to show.
该tzinfo属性显示 utc,但显示的日期和时间是正确的。
UPDATE 30/10/2015(Django 1.8)
更新 30/10/2015(Django 1.8)
I'm using another approach today, that is more django friendly
我今天使用另一种方法,这对 django 更友好
>>> from django.utils import timezone
>>> from trainings.models import Training
>>> value = Training.objects.first().date
>>> value
datetime.datetime(2015, 10, 23, 11, 32, 54, 633151, tzinfo=<UTC>)
>>> timezone.localtime(value)
datetime.datetime(2015, 10, 23, 9, 32, 54, 633151, tzinfo=<django.utils.timezone.LocalTimezone object at 0x7fa6129784a8>)
回答by Rex L
localtimeis a template filter, this may be helpful.
localtime是一个模板过滤器,这可能会有所帮助。
https://github.com/django/django/blob/1.8.4/django/utils/timezone.py#L298
https://github.com/django/django/blob/1.8.4/django/utils/timezone.py#L298
Code sample:
代码示例:
from django.utils.timezone import localtime
desired_datetime = localtime(stored_datetime)
回答by hereischen
I have came to the same problem. In my settings, I have set the TIME_ZONE, but the time in MySql still UTC time.
我遇到了同样的问题。在我的设置中,我已经设置了TIME_ZONE,但 MySql 中的时间仍然是 UTC 时间。
# settings.py
TIME_ZONE = 'Asia/Shanghai'
Then I found,in settings.py, USE_TZhas be set to False
然后我发现,在settings.py中,USE_TZ已经设置为False
USE_TZ = False
USE_TZ = False
As pointed out by @MagicLAMP, it only works for single time zone site, please check time-zonesif your site is international or if daylight savings happen where your site is used.
正如@MagicLAMP 所指出的,它仅适用于单一时区网站,请检查时区是否您的网站是国际性的,或者是否在使用您的网站的地方发生夏令时。
回答by Александр Веклич
Just use
只需使用
timezone.localtime(arg)
回答by scott
It took me a while to find this, but this is how I solved it. I guess the user's timezone from IP address and then do this in Django 2 and beyond:
我花了一段时间才找到这个,但这就是我解决它的方法。我猜用户的时区来自 IP 地址,然后在 Django 2 及更高版本中执行此操作:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ object.date }}
{% endtimezone %}
回答by Vanessa Martins
1: Define the timezone in your view
1:在您的视图中定义时区
from django.utils import timezone
variable = timezone.now()
2: Then use it in your template
2:然后在你的模板中使用它
{% load l10n %}
Teresina, {{variable |localize}}.

