Joelsutilities API
- class joelsutilities.EdgeDetector(initial_value: bool)
Bases:
objectdetect when a boolean value changes from True to False and vice-versa comparing to previous-state value
>>> EdgeDetector(True).current_value True >>> detector.update(True) >>> detector.update(False) >>> detector.rising False >>> detector.falling True >>> detector.update(True) >>> detector.rising True >>> detector.falling False >>> detector.update(True) >>> detector.rising False >>> detector.current_value True
- property current_value: bool
most recent value set by self.update
- property falling: bool
returns True if latest value set by self.update is False but preceeding value True
- property rising: bool
returns True if latest value set by self.update is True but preceeding value False
- class joelsutilities.Registrar
Bases:
Generic[joelsutilities.registrar.T]Registrar dictionary wrapper of unique string to elements
register_namedandregister_elementprovide wrapper functions, typically used as decorators to “register” a function or classDictionary of elements can be accessed using
registrar.get(...),registrar.values()andregistrar.items()Dictionary indexing functions are also available using
... in registrarorregistrar[...]- Parameters
Generic (T) – generic type of object held in dictionary elements
- items() collections.abc.ItemsView[str, joelsutilities.registrar.T]
- register_element(obj: joelsutilities.registrar.T) joelsutilities.registrar.T
register an element using its __name__ attribute, add to dictionary of elements
- values() ValuesView[joelsutilities.registrar.T]
- class joelsutilities.TimeSimulator
Bases:
objectsimulate a timer from a specified start date
- current()
- reset_start(start_date: datetime.datetime)
- seconds_elapsed()
- start()
- stop()
- class joelsutilities.Timer
Bases:
objecttimer that can be started and stopped, with elapsed property denoted time passed since start keeps track of total time elapsed whilst stopping and starting must not try to stop when already stopped, or start when already started
- property elapsed
- reset()
reset elapsed time timer must be stopped
- start()
start timer
- stop()
stop timer
- class joelsutilities.TimingRegistrar(timings: Optional[Dict[str, List[datetime.timedelta]]] = None)
Bases:
object- register_function(func: Callable) Callable
Register a function for execution times to be logged, using function name as the key
- register_method(func: Callable) Callable
Register a function for for execution times to be logged using <class name>.<function name> as the key
- register_named_method(name_attr: str) Callable
Register a function for execution times to be logged, using a custom named key
- property timings
- joelsutilities.closest_index(array: numpy.ndarray, value: Union[float, int]) int
get closest index in numpy array, or -1 if empty
>>> closest_index([1,2,3,4,5], 1.2) 0 >>> closest_index([1,2,3,4,5], -1) 0 >>> closest_index([1,2,3,4,5], 1.6) 1 >>> closest_index([1,2,3,4,5], 999) 4 >>> closest_index([1,2,3,4,5], 2.4) 1 >>> closest_index([1,2,3,4,5], 4.9) 4
- joelsutilities.format_timedelta(td: datetime.timedelta, fmt: str = '{h:02}:{m:02}:{s:02}') str
format timedelta object with format spec
valid format specifiers include:
d: days
h: hours
m: minutes
s: seconds
ms: milliseconds
u: microseconds
- Parameters
td (timedelta) –
timdeltaobjectfmt (str) – string formatter, defaults to “{h:02}:{m:02}:{s:02}”
- Return str
timdeltaobject formatted as a strning
>>> format_timedelta(timedelta(seconds=30, minutes=20)) "00:30:20" >>> format_timedelta(timedelta(days=2, hours=3), '{d} days') "2 days" >>> format_timedelta(timedelta(days=2, hours=3, minutes=4, seconds=5, milliseconds=6), '{d} days {h:02}:{m:02}:{s:02}:{ms:03}') "2 days 03:04:05:006"
- joelsutilities.is_jsonable(x: Any) bool
determine if data can be serialized safely with json.dumps
>>> is_jsonable("some string") True >>> is_jsonable(12345) True >>> is_jsonable(object()) False
- joelsutilities.localise(dt: datetime.datetime, tz_from: typing.Union[pytz.tzinfo.DstTzInfo, pytz.tzinfo.StaticTzInfo] = <UTC>, tz_to=<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>) datetime.datetime
convert naive datetime (default UTC) into local datetime (default London)
- Parameters
dt (datetime.datetime) – datetime input
tz_from (Union[DstTzInfo, StaticTzInfo]) – timezone to convert from, defaults to pytz.UTC
tz_to (_type_) – timzone to convert to, defaults to pytz.timezone(“Europe/London”)
- Raises
DateTimeException – expects datetime to be naive
- Return datetime
timezone aware datetime
>>> localise(datetime.now()).tzinfo == datetime.now(pytz.timezone('Europe/London')).tzinfo True
- joelsutilities.ms_to_datetime(timestamp_ms: Union[int, float]) datetime.datetime
convert millisecond timestamp to datetime in UTC
- Parameters
timestamp_ms (Union[int, float]) – milliseconds timestamp since epoch
- Returns
datetime object
- Return type
datetime
>>> ms_to_datetime(0) == datetime(1970, 1, 1) # epoch is 1st jan 1970 True
- joelsutilities.today(tz: Optional[datetime.tzinfo] = None) datetime.datetime
get datetime of today
- joelsutilities.tomorrow(tz: Optional[datetime.tzinfo] = None) datetime.datetime
get datetime of tomorrow