社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  问与答

用django作一个博客系统,怎么根据当前时间来显示日志发布时间

amghost • 11 年前 • 7482 次点击  

比如,今天2014年1月13号12:40我发布了一篇日志,那到今天为止,访问者访问这篇日志时显示的日志发表时间就是 12:40 当过了今天,就显示 xx月xx日 12:40 当过了今年,就显示xxxx年xx月xx日 12:40

我知道template有date过滤器,但是应该怎么根据当前时间与日志发布时间的差距来动态格式化时间呢?

非常感谢~

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/356
 
7482 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Py站长
Reply   •   1 楼
Py站长    11 年前

一个类似的:

from django import template

from django.core.urlresolvers import reverse

import datetime

from django.template.defaultfilters import timesince as _timesince
from django.template.defaultfilters import date as _date
from django.utils.tzinfo import LocalTimezone
from django.utils.translation import ugettext_lazy as _

from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode

register = template.Library()


@register.filter
def my_timeslice(d, now = None):
    # Convert datetime.date to datetime.datetime for comparison.
    if not d:
        return ''
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)
    if not now:
        if d.tzinfo:
            now = datetime.datetime.now(LocalTimezone(d))
        else:
            now = datetime.datetime.now()
    # ignore microsecond part of 'd' since we removed it from 'now'
    delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since // (60 * 60 * 24) < 3:
        return _("%s ago") % _timesince(d)
    return _date(d, "Y-m-d H:i")
Py站长
Reply   •   2 楼
Py站长    11 年前

写个过滤器,将当前时间减去你写日志的时间,进行判断,如何显示