cast.cast_str_to_timedelta(): Add conversion method

Make cast.from_str() accept time strings.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2025-05-28 11:12:49 +02:00
commit 9c13381e7a
2 changed files with 19 additions and 2 deletions

View file

@ -14,7 +14,7 @@ jw-maintainer = jan
libname = none
[pkg.requires.os]
run = python3-magic, python3-termcolor, mypy
run = mypy, python3-magic, python3-termcolor, python3-pytimeparse
[pkg.requires.jw]
devel = jw-python-run = VERSION-REVISION, jw-build-devel = VERSION

View file

@ -1,3 +1,7 @@
# -*- coding: utf-8 -*-
import pytimeparse
from datetime import datetime, timedelta
from collections import OrderedDict
from .log import *
@ -14,6 +18,17 @@ def _strip(s_, throw=True, log_level=ERR):
slog(log_level, msg)
return None
def cast_str_to_timedelta(s_: str, throw=True, log_level=DEBUG): # export
s = _strip(s_, throw=throw, log_level=log_level)
try:
return (True, timedelta(seconds=pytimeparse.parse(s_)))
except Exception as e:
msg = f'Could not convert string "{s_}" to time ({e})'
if throw:
raise Exception(msg)
slog(log_level, msg)
return (False, None)
def cast_str_to_int(s_: str, throw=True, log_level=DEBUG): # export
s = _strip(s_, throw=throw, log_level=log_level)
if s[0] == '-':
@ -43,7 +58,9 @@ def cast_str_to_bool(s_: str, throw=True, log_level=DEBUG): # export
_str_cast_functions = OrderedDict({
bool: cast_str_to_bool,
int: cast_str_to_int
int: cast_str_to_int,
timedelta: cast_str_to_timedelta
})
def guess_type(s: str, default=None, log_level=DEBUG, throw=False): # export