Joelsutilities API

class joelsutilities.EdgeDetector(initial_value: bool)

Bases: object

detect 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

update(new_value: bool)

update current state boolean value

class joelsutilities.Registrar

Bases: Generic[joelsutilities.registrar.T]

Registrar dictionary wrapper of unique string to elements

register_named and register_element provide wrapper functions, typically used as decorators to “register” a function or class

Dictionary of elements can be accessed using registrar.get(...), registrar.values() and registrar.items()

Dictionary indexing functions are also available using ... in registrar or registrar[...]

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

register_named(name: str)

register an element using a defined name, add to dictionary of elements

values() ValuesView[joelsutilities.registrar.T]
class joelsutilities.TimeSimulator

Bases: object

simulate a timer from a specified start date

current()
reset_start(start_date: datetime.datetime)
seconds_elapsed()
start()
stop()
class joelsutilities.Timer

Bases: object

timer 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

log_result(elapsed_seconds: float, name: str) None

manually add to list of timed functions

Parameters
  • elapsed_seconds (float) – elapsed time value

  • name (str) – function name

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) – timdelta object

  • fmt (str) – string formatter, defaults to “{h:02}:{m:02}:{s:02}”

Return str

timdelta object 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