mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 01:52:56 +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
|
||||
|
||||
[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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue