You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何按事件时区显示Meeting的started_on时间?

Display Meeting Time in Event's Timezone (Django)

Got it, let's get those meeting times showing up in the event's timezone instead of your local one. Here's how to make your started_on_tz method work perfectly in your templates:

Step 1: (Optional but Cleaner) Turn the Method into a Property

First, I'd recommend converting your started_on_tz method into a Python property—this makes it feel more like a regular field when you use it, no need for parentheses in templates. Update your Meeting model like this:

from django.utils import timezone

class Meeting(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    started_on = models.DateTimeField()
    ended_on = models.DateTimeField()
    
    @property
    def started_on_tz(self):
        # Add a fallback in case the event has no timezone set
        if not self.event.time_zone:
            return self.started_on
        return self.started_on.astimezone(timezone(self.event.time_zone))

Step 2: Update Your Template to Use the Timezone-Aware Value

In your template where you were displaying {{ meeting.started_on }}, just replace it with {{ meeting.started_on_tz }}. You can also add Django's date filter to format it nicely, like:

<!-- Example template code -->
<div class="meeting-time">
  Started on: {{ meeting.started_on_tz|date:"F j, Y, g:i A" }}
</div>

Adjust the date format string ("F j, Y, g:i A") to match your desired display style—Django has tons of formatting options for dates and times.

Key Checks to Avoid Issues

  • Make sure event.time_zone stores a valid timezone identifier (like "America/Los_Angeles" or "Europe/London"), not just an offset like -0800. The timezone() function relies on these standard identifiers.
  • Confirm that started_on is indeed timezone-aware (you mentioned it is, but double-check—if your project uses USE_TZ = True in settings, DateTimeFields are timezone-aware by default).

That's it! Your meetings will now show up in the timezone linked to their parent event instead of your server's local timezone.

内容的提问来源于stack exchange,提问作者Atma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:42:52