在django获取当地时区 [英] Get local timezone in django
问题描述
我有一个在系统时间UTC存储的mysql DATETIME
值。我需要把它转换成我的本地时区在django。这是我目前拥有的:
I have a mysql DATETIME
value that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:
# 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
如何获得last_updated值在我的本地时区=美国/洛杉矶?
How would I get the last_updated value to be in my local timezone = "America/Los Angeles" ?
推荐答案
Django文档对于时区记录了将 datetime
对象转换到相应时区显示的所有必要细节。
The Django documentation for timezones documents all the necessary details for converting datetime
objects to the appropriate time zone for display.
您的数据存储在UTC中是好的。当您从数据库获取 DateTime
字段对象时,它将是一个天真的 datetime.datetime
对象。即没有附加时区的日期/时间。
Your data is stored in UTC which is good. When you obtain a DateTime
field object from the database it will be a naive datetime.datetime
object. ie A date/time without a timezone attached. It's then up to you to do the conversion.
您的webapp的用户可能位于不同的时区,因此转换到适当的时区必须发生在每个请求。这就是为什么有一个激活功能的原因设置当前时区。
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 activate function to set the current time zone.
如果您有 pytz 已安装,您应该可以执行以下操作:
If you have pytz installed you should be able to do the following:
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.
如果你只有一个天真的 datetime.datetime
实例,你要设置时区,然后直接使用 pytz
模块。在您的观点中执行此操作并不正常,因为只有在演示时才转换时区才是一个好主意。
If you just have a single naive datetime.datetime
instance that you want to set the time zone on, then just use the pytz
module 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.
from pytz import timezone
settingstime_zone = timezone(settings.TIME_ZONE)
last_updated = last_updated.astimezone(settings_time_zone)
这篇关于在django获取当地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!