mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 09:53:32 +01:00
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:
parent
296dde387c
commit
9c13381e7a
2 changed files with 19 additions and 2 deletions
|
|
@ -14,7 +14,7 @@ jw-maintainer = jan
|
||||||
libname = none
|
libname = none
|
||||||
|
|
||||||
[pkg.requires.os]
|
[pkg.requires.os]
|
||||||
run = python3-magic, python3-termcolor, mypy
|
run = mypy, python3-magic, python3-termcolor, python3-pytimeparse
|
||||||
|
|
||||||
[pkg.requires.jw]
|
[pkg.requires.jw]
|
||||||
devel = jw-python-run = VERSION-REVISION, jw-build-devel = VERSION
|
devel = jw-python-run = VERSION-REVISION, jw-build-devel = VERSION
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,7 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
import pytimeparse
|
||||||
|
from datetime import datetime, timedelta
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
from .log import *
|
from .log import *
|
||||||
|
|
@ -14,6 +18,17 @@ def _strip(s_, throw=True, log_level=ERR):
|
||||||
slog(log_level, msg)
|
slog(log_level, msg)
|
||||||
return None
|
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
|
def cast_str_to_int(s_: str, throw=True, log_level=DEBUG): # export
|
||||||
s = _strip(s_, throw=throw, log_level=log_level)
|
s = _strip(s_, throw=throw, log_level=log_level)
|
||||||
if s[0] == '-':
|
if s[0] == '-':
|
||||||
|
|
@ -43,7 +58,9 @@ def cast_str_to_bool(s_: str, throw=True, log_level=DEBUG): # export
|
||||||
|
|
||||||
_str_cast_functions = OrderedDict({
|
_str_cast_functions = OrderedDict({
|
||||||
bool: cast_str_to_bool,
|
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
|
def guess_type(s: str, default=None, log_level=DEBUG, throw=False): # export
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue