summaryrefslogtreecommitdiff
path: root/searx/utils.py
diff options
context:
space:
mode:
authorBnyro <bnyro@tutanota.com>2025-03-20 21:16:37 +0100
committerMarkus Heiser <markus.heiser@darmarIT.de>2025-03-25 16:48:44 +0100
commit4dfc47584d7c946b9682dc1e4858fae003b16d1f (patch)
tree5dae9c70c914a7462ef302044fd5fc72a783bf0a /searx/utils.py
parentc28d35c7fc34da4e27700610f58c57135fea6310 (diff)
[refactor] duration strings: move parsing logic to utils.py
Diffstat (limited to 'searx/utils.py')
-rw-r--r--searx/utils.py27
1 files changed, 24 insertions, 3 deletions
diff --git a/searx/utils.py b/searx/utils.py
index 8fdcb0fda..ee044704b 100644
--- a/searx/utils.py
+++ b/searx/utils.py
@@ -1,7 +1,5 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
-"""Utility functions for the engines
-
-"""
+"""Utility functions for the engines"""
from __future__ import annotations
@@ -18,6 +16,7 @@ from random import choice
from html.parser import HTMLParser
from html import escape
from urllib.parse import urljoin, urlparse, parse_qs, urlencode
+from datetime import timedelta
from markdown_it import MarkdownIt
from lxml import html
@@ -831,3 +830,25 @@ def js_variable_to_python(js_variable):
s = s.replace(chr(1), ':')
# load the JSON and return the result
return json.loads(s)
+
+
+def parse_duration_string(duration_str: str) -> timedelta | None:
+ """Parse a time string in format MM:SS or HH:MM:SS and convert it to a `timedelta` object.
+
+ Returns None if the provided string doesn't match any of the formats.
+ """
+ duration_str = duration_str.strip()
+
+ if not duration_str:
+ return None
+
+ try:
+ # prepending ["00"] here inits hours to 0 if they are not provided
+ time_parts = (["00"] + duration_str.split(":"))[:3]
+ hours, minutes, seconds = map(int, time_parts)
+ return timedelta(hours=hours, minutes=minutes, seconds=seconds)
+
+ except (ValueError, TypeError):
+ pass
+
+ return None