summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenjamin Wohlwend <piquadrat@gmail.com>2015-03-04 20:24:30 +0100
committerAymeric Augustin <aymeric.augustin@oscaro.com>2015-03-04 22:31:27 +0100
commit3bc35f7e08cd1752722a37c70c295d373e7214a8 (patch)
tree0b7bee61f9f54fa0d09dc6f206e62017adc793a0
parent20bf3205027fe581b8f33cd98b164f16a801c813 (diff)
[1.8.x] Moved definition of chunks out of timesince function.
This speeds up the timesince function/filter substantially. Backport of d6969ab from master.
-rw-r--r--django/utils/timesince.py23
1 files changed, 12 insertions, 11 deletions
diff --git a/django/utils/timesince.py b/django/utils/timesince.py
index b39ab203a7..b4ae61e4d9 100644
--- a/django/utils/timesince.py
+++ b/django/utils/timesince.py
@@ -6,6 +6,15 @@ from django.utils.html import avoid_wrapping
from django.utils.timezone import is_aware, utc
from django.utils.translation import ugettext, ungettext_lazy
+TIMESINCE_CHUNKS = (
+ (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')),
+ (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')),
+ (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')),
+ (60 * 60 * 24, ungettext_lazy('%d day', '%d days')),
+ (60 * 60, ungettext_lazy('%d hour', '%d hours')),
+ (60, ungettext_lazy('%d minute', '%d minutes'))
+)
+
def timesince(d, now=None, reversed=False):
"""
@@ -21,14 +30,6 @@ def timesince(d, now=None, reversed=False):
Adapted from
http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
"""
- chunks = (
- (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')),
- (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')),
- (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')),
- (60 * 60 * 24, ungettext_lazy('%d day', '%d days')),
- (60 * 60, ungettext_lazy('%d hour', '%d hours')),
- (60, ungettext_lazy('%d minute', '%d minutes'))
- )
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
@@ -44,14 +45,14 @@ def timesince(d, now=None, reversed=False):
if since <= 0:
# d is in the future compared to now, stop processing.
return avoid_wrapping(ugettext('0 minutes'))
- for i, (seconds, name) in enumerate(chunks):
+ for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
count = since // seconds
if count != 0:
break
result = avoid_wrapping(name % count)
- if i + 1 < len(chunks):
+ if i + 1 < len(TIMESINCE_CHUNKS):
# Now get the second item
- seconds2, name2 = chunks[i + 1]
+ seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
count2 = (since - (seconds * count)) // seconds2
if count2 != 0:
result += ugettext(', ') + avoid_wrapping(name2 % count2)