简体   繁体   English

在Django中使用给定时区显示时间

[英]Display a time using a given timezone in Django

I'm developing a Django app for logging dives and each dive has a datetime and a timezone in it. 我正在开发一个用于记录潜水的Django应用,每次潜水都有一个日期时间和一个时区。 I'm using the django-timezone-field app for the timezone. 我正在使用django-timezone-field应用程序作为时区。

class Dive(models.Model):
  ...
  date_time_in = models.DateTimeField(default=timezone.now)
  timezone = TimeZoneField(default=timezone.get_current_timezone_name())

So the user is able to enter a datetime string ("2016-07-11 14:00") and select a timezone ("Asia/Bangkok" - UTC+0700), I then set the timezone of the datetime to the one given in my view like this: 这样用户可以输入日期时间字符串(“ 2016-07-11 14:00”)并选择时区(“亚洲/曼谷”-UTC + 0700),然后将日期时间的时区设置为给定的时区在我看来是这样的:

def log_dive(request):
  if request.method == 'POST':
    form = DiveForm(request.POST)
    if form.is_valid():
      dive = form.save(commit=False)
      date = dive.date_time_in
      date = date.replace(tzinfo=None)
      dive.date_time_in = dive.timezone.localize(date)
      dive.save()

The database then stores the datetime as UTC in the database (SELECT statement gives it in my local timezone): 然后,数据库将日期时间以UTC格式存储在数据库中(SELECT语句在我的本地时区中给出了日期时间):

# SELECT date_time_in, timezone FROM divelog_dive ORDER BY number DESC;
      date_time_in      |     timezone     
------------------------+------------------
 2014-07-11 17:00:00+10 | Asia/Bangkok

Now there are two things I'm struggling with: 现在,我有两件事要努力解决:

1) I want to display the dates in the given timezone, however I can't seem to stop it defaulting to the TIME_ZONE setting. 1)我想显示给定时区中的日期,但是我似乎无法停止将其默认为TIME_ZONE设置。

2) If the user edits the record, the time displayed in the edit field should be the one they originally entered (14:00), instead it's showing it in the current timezone (17:00). 2)如果用户编辑记录,则在编辑字段中显示的时间应该是他们最初输入的时间(14:00),而是将其显示在当前时区(17:00)。

settings.py检查您的时区settings.py

Do you have USE_TZ = true in your settings file? 您的设置文件中是否有USE_TZ = true? If you created your app using the djangoadmin-startproject command, it is set by default. 如果使用djangoadmin-startproject命令创建了应用程序,则默认情况下将其设置。

Also, I struggled with timezones at my last job but found that using pytz really helped. 另外,我在上一份工作中与时区作斗争,但发现使用pytz确实有帮助。 Have you tried that package yet? 你试过那个包了吗?

EDIT: Ok man I may be way off, but since noone else has answered and I feel the timezone struggle, here is something I noticed... 编辑:好的,我可能还很遥远,但是由于没有其他人回答,而且我感到时区很挣扎,所以我注意到了这一点...

You are replacing the date object with tz_info=None, but wouldn't you want to instead replace that with the timezone from the database? 您要用tz_info = None替换日期对象,但是您不是要用数据库中的时区替换日期对象吗? So you would get that timezone and do a replace using the valid format (tzinfo=blah...)? 因此,您将获得该时区并使用有效格式(tzinfo = blah ...)进行替换? Like I said I may be way off but if that helps there you go. 就像我说的那样,我可能还有一段路要走,但如果有帮助,您就可以走了。

Sorry, I don't think I explained my problem very well. 抱歉,我认为我不能很好地解释我的问题。 I finally figured this out, so I'll answer my own question. 我终于想通了,所以我将回答我自己的问题。

1) turned out to be easy, Django have a template tag for displaying times in a given zone: 1)事实证明很容易,Django有一个模板标签用于显示给定区域中的时间:

{{ dive.date_time_in|timezone:dive.timezone|date:"Y-m-d H:i e" }}

For 2), I came across [1] which lead me to this solution: In the view, after getting the object from the database, I use astimezone(...) to convert the date value (which the DB stores as UTC) into the given timezone. 对于2),我碰到了[1],这引出了我这个解决方案:在视图中,从数据库中获取对象之后,我使用astimezone(...)转换日期值(数据库将其存储为UTC)进入给定的时区。 I then use replace(tzinfo=None) to make it naive and then it displays correctly on my form. 然后,我使用replace(tzinfo = None)使它天真,然后在我的表单上正确显示。

def edit_dive(request, dive_id=None):
  dive = None
  if dive_id != None:
    dive = get_object_or_404(Dive, pk=dive_id)
    local_date = dive.date_time_in.astimezone(timezone(str(dive.timezone)))
    dive.date_time_in = local_date.replace(tzinfo=None)

[1] http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/ [1] http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/

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

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