diff options
Diffstat (limited to 'searx/utils.py')
| -rw-r--r-- | searx/utils.py | 27 |
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 |