Ticket #12771: humanize+naturaltime.diff

File humanize+naturaltime.diff, 2.1 KB (added by phinpho, 5 years ago)

patch for templatetag naturaltime

  • django/contrib/humanize/templatetags/humanize.py

     
    22from django.utils.encoding import force_unicode
    33from django import template
    44from django.template import defaultfilters
    5 from datetime import date
     5from datetime import date, datetime
    66import re
    77
    88register = template.Library()
     
    1414    """
    1515    try:
    1616        value = int(value)
    17     except (TypeError, ValueError):
     17    except ValueError:
    1818        return value
    1919    t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th'))
    2020    if value % 100 in (11, 12, 13): # special case
     
    9797        return _(u'yesterday')
    9898    return defaultfilters.date(value, arg)
    9999register.filter(naturalday)
     100
     101def naturaltime(value, arg=None):
     102    """
     103    For date and time values shows how many seconds, minutes or hours ago compared to
     104    current timestamp returns representing string. Otherwise, returns a string
     105    formatted according to settings.DATE_FORMAT
     106    """
     107    try:
     108        value = datetime(value.year, value.month, value.day, value.hour, value.minute, value.second)
     109    except AttributeError:
     110        return value
     111    except ValueError:
     112        return value
     113   
     114    delta = datetime.now() - value
     115    if delta.days != 0:
     116        value = date(value.year, value.month, value.day)
     117        return naturalday(value, arg)
     118    elif delta.seconds == 0:
     119        return _(u'now')
     120    elif delta.seconds < 60:
     121        return _(u"%s seconds ago" % (delta.seconds))
     122    elif delta.seconds / 60 < 2:
     123        return _(r'a minute ago')
     124    elif delta.seconds / 60 < 60:
     125        return _(u"%s minutes ago" % (delta.seconds/60))
     126    elif delta.seconds / 60 / 60 < 2:
     127        return _(u'an hour ago')
     128    elif delta.seconds / 60 / 60 < 24:
     129        return _(u"%s hours ago" % (delta.seconds/60/60))
     130    return naturalday(value, arg)
     131register.filter(naturaltime)
Back to Top