Code

Ticket #12771: humanize+naturaltime.diff

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

patch for templatetag naturaltime

Line 
1Index: django/contrib/humanize/templatetags/humanize.py
2===================================================================
3--- django/contrib/humanize/templatetags/humanize.py    (revisão 12380)
4+++ django/contrib/humanize/templatetags/humanize.py    (cópia de trabalho)
5@@ -2,7 +2,7 @@
6 from django.utils.encoding import force_unicode
7 from django import template
8 from django.template import defaultfilters
9-from datetime import date
10+from datetime import date, datetime
11 import re
12 
13 register = template.Library()
14@@ -14,7 +14,7 @@
15     """
16     try:
17         value = int(value)
18-    except (TypeError, ValueError):
19+    except ValueError:
20         return value
21     t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th'))
22     if value % 100 in (11, 12, 13): # special case
23@@ -97,3 +97,35 @@
24         return _(u'yesterday')
25     return defaultfilters.date(value, arg)
26 register.filter(naturalday)
27+
28+def naturaltime(value, arg=None):
29+    """
30+    For date and time values shows how many seconds, minutes or hours ago compared to
31+    current timestamp returns representing string. Otherwise, returns a string
32+    formatted according to settings.DATE_FORMAT
33+    """
34+    try:
35+        value = datetime(value.year, value.month, value.day, value.hour, value.minute, value.second)
36+    except AttributeError:
37+        return value
38+    except ValueError:
39+        return value
40+   
41+    delta = datetime.now() - value
42+    if delta.days != 0:
43+        value = date(value.year, value.month, value.day)
44+        return naturalday(value, arg)
45+    elif delta.seconds == 0:
46+        return _(u'now')
47+    elif delta.seconds < 60:
48+        return _(u"%s seconds ago" % (delta.seconds))
49+    elif delta.seconds / 60 < 2:
50+        return _(r'a minute ago')
51+    elif delta.seconds / 60 < 60:
52+        return _(u"%s minutes ago" % (delta.seconds/60))
53+    elif delta.seconds / 60 / 60 < 2:
54+        return _(u'an hour ago')
55+    elif delta.seconds / 60 / 60 < 24:
56+        return _(u"%s hours ago" % (delta.seconds/60/60))
57+    return naturalday(value, arg)
58+register.filter(naturaltime)