From bbc215bfb6e0d78e295b117135d2076733e7761c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Thu, 17 Aug 2023 13:44:59 +0200 Subject: [PATCH] misc: add months and years to duration (#80421) --- publik_django_templatetags/publik/utils.py | 12 ++++++++++++ tests/test_publik.py | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/publik_django_templatetags/publik/utils.py b/publik_django_templatetags/publik/utils.py index bbc444f..8fb8a06 100644 --- a/publik_django_templatetags/publik/utils.py +++ b/publik_django_templatetags/publik/utils.py @@ -21,6 +21,8 @@ from django.utils.translation import ngettext_lazy _minute = 60 _hour = 60 * 60 _day = _hour * 24 +_month = _day * 31 +_year = int(_day * 365.25) def list2human(stringlist): @@ -36,6 +38,11 @@ def seconds2humanduration(seconds, short=False): if not isinstance(seconds, int): return '' + if not short: + years = int(seconds / _year) + seconds = seconds - _year * years + months = int(seconds / _month) + seconds = seconds - _month * months days = int(seconds / _day) seconds = seconds - _day * days hours = int(seconds / _hour) @@ -43,6 +50,11 @@ def seconds2humanduration(seconds, short=False): minutes = int(seconds / _minute) seconds = seconds - _minute * minutes human = [] + if not short: + if years: + human.append(ngettext_lazy('%(total)s year', '%(total)s years', years) % {'total': years}) + if months: + human.append(ngettext_lazy('%(total)s month', '%(total)s months', months) % {'total': months}) if days: human.append(ngettext_lazy('%(total)s day', '%(total)s days', days) % {'total': days}) if short: diff --git a/tests/test_publik.py b/tests/test_publik.py index 9ef4ff5..f9e3679 100644 --- a/tests/test_publik.py +++ b/tests/test_publik.py @@ -363,3 +363,15 @@ def test_duration(): context = Context({'value': 'xx'}) assert Template('{{ value|duration }}').render(context) == '' assert Template('{{ value|duration:"long" }}').render(context) == '' + + context = Context({'value': 10_000_000}) + assert ( + Template('{{ value|duration:"long" }}').render(context) + == '3 months, 22 days, 17 hours, 46 minutes and 40 seconds' + ) + + context = Context({'value': 100_000_000}) + assert ( + Template('{{ value|duration:"long" }}').render(context) + == '3 years, 1 month, 30 days, 15 hours, 46 minutes and 40 seconds' + )