76 lines
2.9 KiB
Python
76 lines
2.9 KiB
Python
# publik-django-templatetags
|
|
# Copyright (C) 2023 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
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):
|
|
'''Transform a string list to human enumeration'''
|
|
beginning = stringlist[:-1]
|
|
if not beginning:
|
|
return ''.join(stringlist)
|
|
return _('%(first)s and %(second)s') % {'first': _(', ').join(beginning), 'second': stringlist[-1]}
|
|
|
|
|
|
def seconds2humanduration(seconds, short=False):
|
|
"""Convert a time range in seconds to a human string representation"""
|
|
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)
|
|
seconds = seconds - _hour * hours
|
|
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:
|
|
if hours and minutes:
|
|
human.append(_('%(hours)sh%(minutes)02d') % {'hours': hours, 'minutes': minutes})
|
|
elif hours:
|
|
human.append(_('%(hours)sh') % {'hours': hours})
|
|
elif minutes:
|
|
human.append(_('%(minutes)smin') % {'minutes': minutes})
|
|
return list2human(human)
|
|
else:
|
|
if hours:
|
|
human.append(ngettext_lazy('%(total)s hour', '%(total)s hours', hours) % {'total': hours})
|
|
if minutes:
|
|
human.append(ngettext_lazy('%(total)s minute', '%(total)s minutes', minutes) % {'total': minutes})
|
|
if seconds:
|
|
human.append(ngettext_lazy('%(total)s second', '%(total)s seconds', seconds) % {'total': seconds})
|
|
return list2human(human)
|