Issues with time across different time zone

Hi everyone, I’ve encountered a strange issue. Here is my model function:

# Create your models here.
class Post(models.Model):
    """创建帖子对象"""
    class Status(models.TextChoices):
        PUBLISHED = "PB","published"
        DRAFT = "DF","Draft"
        EDIT = "ED","Edit"
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    #标题
    title = models.CharField(max_length=50)
    #创建对搜索引擎友好的片段
    slug = models.SlugField(max_length=50,unique=True)
    #发布时间
    published = models.DateTimeField(default=timezone.now)
    #更新时间
    updated = models.DateTimeField(auto_now_add=True)
    #帖子状态
    status = models.CharField(
        max_length=2,
        choices=Status,
        default=Status.DRAFT   
    )

    #帖子正文
    body = models.TextField()

    #定义元素具
    class Meta:
        ordering = ["-published"]   #以默认创建帖子的时间排序
        #创建优化索引
        indexes = [
            models.Index(fields=['title']),
        ]


    def __str__(self):
        """返回标题"""
        return self.title
    
    def get_absolute_url(self):
        return reverse(
            "blog:post_detail",
            args=[
                self.published.year,
                self.published.month,
                self.published.day,
                self.slug
            ]
        )

Here is the view function for finding a specific post:

def post_detail(request,year,month,day,post):
    """帖子详情"""
    try:
        print(f"查找参数: year={year}, month={month}, day={day}, slug={post},title={post.title}")
        post = Post._default_manager.get(
            published__year=year,
            published__month=month,
            published__day=day,
            slug=post
            )
        print(f"找到帖子: {post.title}")
    except Post.DoesNotExist:
        raise Http404("未找到帖子")
    return render(
        request,
        "blog/post_detail.html",
        {
            "post":post
        }
    )

The issue is in this line: published = models.DateTimeField(default=timezone.now) . This is because I modified the timezone setting in the [settings.py] file.

LANGUAGE_CODE = "zh-hans"

TIME_ZONE = "Asia/ShangHai"

USE_I18N = True

USE_TZ = True

A strange phenomenon occurs when I create posts in the evening:
Below is a post created on June 12, 2025.


However, when I click into it, these warnings appear:

Page not found (404)
未找到帖子
Request Method:	GET
Request URL:	http://localhost:8001/blog/post/2025/6/11/asdsacasc/detail/
Raised by:	blog.views.post_detail
Using the URLconf defined in my_project_settings.urls, Django tried these URL patterns, in this order:

admin/
blog/ [name='post_list']
blog/ user_posts/<int:id>/posts [name='user_posts']
blog/ post/<int:year>/<int:month>/<int:day>/<slug:post>/detail/ [name='post_detail']
The current path, blog/post/2025/6/11/asdsacasc/detail/, matched the last one.

It shows that the post was not found, and the date displayed is June 11, 2025. What’s going on? I tested the post’s published time in the python manage.py shell

>>> post.title
'asdsacasc'
>>> post.published
datetime.datetime(2025, 6, 11, 17, 42, 41, 988920, tzinfo=datetime.timezone.utc)

Why is it June 11th?

Why is this happening? I hope everyone can help me! Thank you all!

My admin site displays the creation time of posts:
image

Hello, Datetimes are stored in database.in the UTC timezone, hence the value returned by

When the date is displayed in the admin, it is converted to current timezone. Also when using datetimes lookups in the databse, the datetimes are converted to the current timezone (see QuerySet API reference | Django documentation | Django).

In your case, the date parts coming from the URL are in the UTC timezone, so it doesn’t match with the date filtering in database which is done in the ShangHai timezone.

To get a correct match, your URL must be generated in the current timezone. To do that, in get_absolute_url, you can first convert the published date to current timezone before generating URL from this new datetime:

local_published_datetime = self.published.astimezone(timezone.get_current_timezone())
2 Likes