From: Michael Tremer Date: Fri, 14 Feb 2025 10:22:26 +0000 (+0000) Subject: web: Use babel to format time deltas X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=170a5a75b886a1e9f5de8c3aca21cb7846b24017;p=pbs.git web: Use babel to format time deltas Signed-off-by: Michael Tremer --- diff --git a/configure.ac b/configure.ac index b7c6d53a..1119386f 100644 --- a/configure.ac +++ b/configure.ac @@ -81,6 +81,7 @@ m4_pattern_forbid([^_?PKG_[A-Z_]+$],[*** pkg.m4 missing, please install pkg-conf AX_PYTHON_MODULE([aiofiles], [fatal]) AX_PYTHON_MODULE([alembic], [fatal]) AX_PYTHON_MODULE([asyncpg], [fatal]) +AX_PYTHON_MODULE([babel], [fatal]) AX_PYTHON_MODULE([boto3], [fatal]) AX_PYTHON_MODULE([cryptography], [fatal]) AX_PYTHON_MODULE([jinja2], [fatal]) diff --git a/src/web/filters.py b/src/web/filters.py index 438f6e30..ce349d85 100644 --- a/src/web/filters.py +++ b/src/web/filters.py @@ -18,6 +18,7 @@ # # ############################################################################### +import babel.dates import datetime import email.utils import jinja2 @@ -79,39 +80,15 @@ def format_day(ctx, *args, **kwargs): return locale.format_day(*args, **kwargs) @jinja2.pass_context -def format_time(ctx, s, shorter=False): +def format_time(ctx, delta, shorter=False): # Fetch locale locale = ctx.get("locale") - # Fetch the translation function - _ = locale.translate - - # Convert into seconds - if isinstance(s, datetime.timedelta): - s = s.total_seconds() - - args = { - "s" : round(s % 60), - "m" : round(s / 60 % 60), - "h" : round(s / 3600 % 3600), - "d" : round(s / 86400), - } - - # Less than one minute - if s < 60: - return _("%(s)d s") % args - - # Less than one hour - elif s < 3600: - return _("%(m)d:%(s)02d m") % args - - # Less than one day - elif s < 86400: - return _("%(h)d:%(m)02d h") % args - - # More than one day - else: - return _("%(d)d:%(h)02d d") % args + return babel.dates.format_timedelta( + delta, + locale = locale.code, + format = "short" if shorter else "long", + ) def highlight(text, filename=None): # Find a lexer