API docs

mplugin

exception mplugin.CheckError[source]

Bases: RuntimeError

Abort check execution.

This exception should be raised if a plugin is unable to determine the system status. Raising this exception will cause the plugin to display the exception’s argument and exit with an UNKNOWN (3) status.

exception mplugin.Timeout[source]

Bases: RuntimeError

Maximum check run time exceeded.

This exception is raised internally by mplugin if the runtime check takes longer than allowed. The check is aborted and the plugin exits with an UNKNOWN (3) status.

class mplugin.ServiceState(code: int, text: str)[source]

Bases: object

Abstract base class for all states.

Each state has two constant attributes:

  • code is the corresponding exit code.

  • text is the short text representation which is printed for example at the beginning of the summary line.

Parameters:
  • code – The Plugin API compliant exit code. Must be 0, 1, 2 or 3.

  • text – The short text representation that is printed, for example, at the beginning of the summary line.

code: int

The Plugin API compliant exit code. Must be 0, 1, 2 or 3.

text: str

The short text representation that is printed, for example, at the beginning of the summary line.

static worst(states: list[ServiceState]) ServiceState[source]

Reduce list of states to the most significant state.

static state(exit_code: int) ServiceState[source]

Convert an exit code to a ServiceState.

Parameters:

exit_code – The exit code to convert. Must be 0, 1, 2 or 3.

Returns:

The corresponding ServiceState (ok, warn, critical, or unknown).

Raises:

CheckError – If exit_code is greater than 3.

mplugin.ok: ServiceState

The plugin was able to check the service and it appeared to be functioning properly.

mplugin.warning: ServiceState

The plugin was able to check the service, but it appeared to be above some warning threshold or did not appear to be working properly.

mplugin.critical: ServiceState

The plugin detected that either the service was not running or it was above some critical threshold.

mplugin.unknown: ServiceState

Invalid command line arguments were supplied to the plugin or low-level failures internal to the plugin (such as unable to fork, or open a tcp socket) that prevent it from performing the specified operation. Higher-level errors (such as name resolution errors, socket timeouts, etc) are outside of the control of plugins and should generally NOT be reported as unknown states.

The --help or --version output should also result in unknown state.

class mplugin.Range(spec: str | int | float | Range | None = None, invert: bool | None = None, start: float | None = None, end: float | None = None)[source]

Bases: object

Represents a threshold range.

The general format is [@][start:][end]. start: may be omitted if start==0. ~: means that start is negative infinity. If end is omitted, infinity is assumed. To invert the match condition, prefix the range expression with @.

Parameters:
  • spec – may be either a string, a float, or another Range object.

  • invert – If the true, the value exceeds the threshold if it is INSIDE the range between start and end (including the endpoints).

  • start – The (inclusive) start point on a numeric scale (possibly negative or negative infinity).

  • end – The (inclusive) end point on a numeric scale (possibly negative or positive infinity).

start: float

The (inclusive) start point on a numeric scale (possibly negative or negative infinity).

end: float

The (inclusive) end point on a numeric scale (possibly negative or positive infinity).

invert: bool

If the true, the value exceeds the threshold if it is INSIDE the range between start and end (including the endpoints).

match(value: float) bool[source]

Decides if value is inside/outside the threshold.

Returns:

True if value is inside the bounds for non-inverted Ranges.

Also available as in operator.

property violation: str

Human-readable description why a value does not match.

class mplugin.Performance(label: str, value: Any, uom: str | None = None, warn: str | int | float | Range | None = None, crit: str | int | float | Range | None = None, min: float | None = None, max: float | None = None)[source]

Bases: object

Performance data (perfdata) representation.

Performance data are created during metric evaluation in a context and are written into the perfdata section of the plugin’s output. Performance allows the creation of value objects that are passed between other mplugin objects.

For sake of consistency, performance data should represent their values in their respective base unit, so Performance('size', 10000, 'B') is better than Performance('size', 10, 'kB').

Parameters:
  • label – The short identifier, results in graph titles for example (20 chars or less recommended).

  • value – The measured value (usually an int, float, or bool).

  • uom – The unit of measure – use base units whereever possible.

  • warn – The warning range.

  • crit – The critical range.

  • min – The known value minimum (None for no minimum).

  • max – The known value maximum (None for no maximum).

label: str

The short identifier, results in graph titles for example (20 chars or less recommended).

value: Any

The measured value (usually an int, float, or bool).

uom: str | None

The unit of measure – use base units whereever possible.

warn: str | int | float | Range | None

The warning range.

crit: str | int | float | Range | None

The critical range.

min: float | None

The known value minimum (None for no minimum).

max: float | None

The known value maximum (None for no maximum).

mplugin.guarded(original_function: Any = None, verbose: Any = None) Any[source]

Runs a function mplugin’s Runtime environment.

guarded makes the decorated function behave correctly with respect to the monitoring plugin API if it aborts with an uncaught exception or a timeout. It exits with an unknown exit code and prints a traceback in a format acceptable by monitoring solution.

This function should be used as a decorator for the script’s main function.

Parameters:

verbose – Optional keyword parameter to control verbosity level during early execution (before main() has been called). For example, use @guarded(verbose=0) to turn tracebacks in that phase off.

class mplugin.Metric(name: str, value: Any, uom: str | None = None, min: float | None = None, max: float | None = None, context: str | Context | None = None, resource: Resource | None = None)[source]

Bases: object

Single measured value. Structured representation for data points.

Instances of ths class are passed as value objects between most of mplugin’s core classes. Typically, Resource objects emit a list of metrics as result of their probe() methods.

The value should be expressed in terms of base units, so Metric('swap', 10240, 'B') is better than Metric('swap', 10, 'kiB').

Parameters:
  • name – A short internal identifier for the value – appears also in the performance data.

  • value – A data point. This value vsually has a boolen or numeric type, but other types are also possible.

  • uomunit of measure, preferrably as ISO abbreviation like s.

  • min – The minimum value or None if there is no known minimum.

  • max – The maximum value or None if there is no known maximum.

  • context – The name of the associated Context (defaults to the metric’s name if left out).

name: str

A short internal identifier for the value – appears also in the performance data.

value: Any

A data point. This value vsually has a boolen or numeric type, but other types are also possible.

uom: str | None

unit of measure, preferrably as ISO abbreviation like s.

min: float | None

The minimum value or None if there is no known minimum.

max: float | None

The maximum value or None if there is no known maximum.

context_name: str

The name of the associated Context (defaults to the metric’s name if left out).

property resource: Resource
property context: Context
property description: str | None

Human-readable, detailed string representation.

Delegates to the Context to format the value.

Returns:

describe() output or valueunit if no context has been associated yet

property valueunit: str

Compact string representation.

This is just the value and the unit. If the value is a real number, express the value with a limited number of digits to improve readability.

evaluate() Result | ServiceState[source]

Evaluates this instance according to the context.

Returns:

Result object

Raises:

RuntimeError – if no context has been associated yet

performance() list[Performance][source]

Generates performance data according to the context.

Returns:

Performance object

Raises:

RuntimeError – if no context has been associated yet

class mplugin.Resource[source]

Bases: object

Abstract base class for custom domain models.

Domain model for data acquisition.

Resource is the base class for the plugin’s domain model. It shoul model the relevant details of reality that a plugin is supposed to check. The Check controller calls Resource.probe() on all passed resource objects to acquire data.

Plugin authors should subclass Resource and write whatever methods are needed to get the interesting bits of information. The most important resource subclass should be named after the plugin itself.

Subclasses may add arguments to the constructor to parametrize information retrieval.

property name: str
probe() list[Metric] | Metric | Generator[Metric, None, None][source]

Query system state and return metrics.

This is the only method called by the check controller. It should trigger all necessary actions and create metrics.

A plugin can perform several measurements at once.

def probe(self):
    self.users = self.list_users()
    self.unique_users = set(self.users)
    return [
        Metric("total", len(self.users), min=0, context="users"),
        Metric("unique", len(self.unique_users), min=0, context="users"),
    ]

Alternatively, the probe() method can act as generator and yield metrics:

def probe(self):
    self.users = self.list_users()
    self.unique_users = set(self.users)
    yield Metric('total', len(self.users), min=0,
                            context='users')
    yield Metric('unique', len(self.unique_users), min=0,
                            context='users')]
Returns:

list of Metric objects, or generator that emits Metric objects, or single Metric object

class mplugin.Result(state: ServiceState, hint: str | None = None, metric: Metric | None = None)[source]

Bases: object

Evaluation outcome consisting of state and explanation.

A Result object is typically emitted by a Context object and represents the outcome of an evaluation. It contains a ServiceState as well as an explanation. Plugin authors may subclass Result to implement specific features.

Outcomes from evaluating metrics in contexts.

The Result class is the base class for all evaluation results. The Results class (plural form) provides a result container with access functions and iterators.

Plugin authors may create their own Result subclass to accomodate for special needs.

state: ServiceState
hint: str | None
metric: Metric | None
property resource: Resource | None

Reference to the resource used to generate this result.

property context: Context | None

Reference to the metric used to generate this result.

class mplugin.Results(*results: Result)[source]

Bases: object

Container for result sets.

Basically, this class manages a set of results and provides convenient access methods by index, name, or result state. It is meant to make queries in Summary implementations compact and readable.

The constructor accepts an arbitrary number of result objects and adds them to the container.

results: list[Result]
by_state: dict[ServiceState, list[Result]]
by_name: dict[str, Result]
add(*results: Result) Self[source]

Adds more results to the container.

Besides passing Result objects in the constructor, additional results may be added after creating the container.

Raises:

ValueError – if result is not a Result object

property most_significant_state: ServiceState

The “worst” state found in all results.

Returns:

ServiceState object

Raises:

ValueError – if no results are present

property most_significant: list[Result]

Returns list of results with most significant state.

From all results present, a subset with the “worst” state is selected.

Returns:

list of Result objects or empty list if no results are present

property first_significant: Result

Selects one of the results with most significant state.

Returns:

Result object

Raises:

IndexError – if no results are present

class mplugin.Summary[source]

Bases: object

Creates a summary formatter object.

Create status line from results.

This module contains the Summary class which serves as base class to get a status line from the check’s Results. A Summary object is used by Check to obtain a suitable data presentation depending on the check’s overall state.

Plugin authors may either stick to the default implementation or subclass it to adapt it to the check’s domain. The status line is probably the most important piece of text returned from a check: It must lead directly to the problem in the most concise way. So while the default implementation is quite usable, plugin authors should consider subclassing to provide a specific implementation that gets the output to the point.

This base class takes no parameters in its constructor, but subclasses may provide more elaborate constructors that accept parameters to influence output creation.

ok(results: Results) str[source]

Formats status line when overall state is ok.

The default implementation returns a string representation of the first result.

Parameters:

resultsResults container

Returns:

status line

problem(results: Results) str[source]

Formats status line when overall state is not ok.

The default implementation returns a string representation of te first significant result, i.e. the result with the “worst” state.

Parameters:

resultsResults container

Returns:

status line

verbose(results: Results) str | list[str] | tuple[str, ...][source]

Provides extra lines if verbose plugin execution is requested.

The default implementation returns a list of all resources that are in a non-ok state.

Parameters:

resultsResults container

Returns:

list of strings

empty() Literal['no check results'][source]

Formats status line when the result set is empty.

Returns:

status line

class mplugin.Context(name: str, fmt_metric: str | Callable[[Metric, Context], str] | None = None)[source]

Bases: object

Creates generic context identified by name.

Metadata about metrics to perform data evaluation.

This module contains the Context class, which is the base for all contexts. ScalarContext is an important specialization to cover numeric contexts with warning and critical thresholds. The Check controller selects a context for each Metric by matching the metric’s context attribute with the context’s name. The same context may be used for several metrics.

Plugin authors may just use to ScalarContext in the majority of cases. Sometimes is better to subclass Context instead to implement custom evaluation or performance data logic.

Generic contexts just format associated metrics and evaluate always to ok. Metric formatting is controlled with the fmt_metric attribute. It can either be a string or a callable. See the describe() method for how formatting is done.

Parameters:
  • name – A context name that is matched by the context attribute of Metric

  • fmt_metric – string or callable to convert context and associated metric to a human readable string

name: str
fmt_metric: str | Callable[[Metric, Context], str] | None
evaluate(metric: Metric, resource: Resource) Result | ServiceState[source]

Determines state of a given metric.

This base implementation returns ok in all cases. Plugin authors may override this method in subclasses to specialize behaviour.

Parameters:
  • metric – associated metric that is to be evaluated

  • resource – resource that produced the associated metric (may optionally be consulted)

Returns:

Result or ServiceState object

result(state: ServiceState, hint: str | None = None, metric: Metric | None = None) Result[source]

Create a Result object with the given state, hint, and metric.

Parameters:
  • state – The service state for the result.

  • hint – An optional hint message providing additional context.

  • metric – An optional Metric object associated with the result.

Returns:

A Result object containing the provided state, hint, and metric.

ok(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a successful Result.

Parameters:
  • hint – Optional hint message providing additional context about the successful operation.

  • metric – Optional Metric object associated with this result.

Returns:

A Result object representing a successful operation.

warning(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a warning result.

Parameters:
  • hint – Optional hint message to provide additional context for the warning.

  • metric – Optional metric associated with the warning.

Returns:

A Result object representing a warning.

critical(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a critical result.

Parameters:
  • hint – Optional hint message providing additional context about the critical result.

  • metric – Optional metric object associated with this critical result.

Returns:

A Result object representing a critical state.

unknown(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a Result object with an unknown status.

Parameters:
  • hint – Optional hint message providing additional context about why the result is unknown

  • metric – Optional Metric object associated with this result

Returns:

A Result object with unknown status

performance(metric: Metric, resource: Resource) Performance | Sequence[Performance] | Generator[Performance, Any, None] | None[source]

Derives performance data from a given metric.

This base implementation just returns none. Plugin authors may override this method in subclass to specialize behaviour.

def performance(self, metric: Metric, resource: Resource) -> Performance:
    return Performance(label=metric.name, value=metric.value)
def performance(
    self, metric: Metric, resource: Resource
) -> Performance | None:
    if not opts.performance_data:
        return None
    return Performance(
        metric.name,
        metric.value,
        metric.uom,
        self.warning,
        self.critical,
        metric.min,
        metric.max,
    )
Parameters:
  • metric – associated metric from which performance data are derived

  • resource – resource that produced the associated metric (may optionally be consulted)

Returns:

Performance object or None

describe(metric: Metric) str | None[source]

Provides human-readable metric description.

Formats the metric according to the fmt_metric attribute. If fmt_metric is a string, it is evaluated as format string with all metric attributes in the root namespace. If fmt_metric is callable, it is called with the metric and this context as arguments. If fmt_metric is not set, this default implementation does not return a description.

Plugin authors may override this method in subclasses to control text output more tightly.

Parameters:

metric – associated metric

Returns:

description string or None

class mplugin.ScalarContext(name: str, warning: str | int | float | Range | None = None, critical: str | int | float | Range | None = None, fmt_metric: str | Callable[[Metric, Context], str] = '{name} is {valueunit}')[source]

Bases: Context

warn_range: Range
critical_range: Range
evaluate(metric: Metric, resource: Resource) Result[source]

Compares metric with ranges and determines result state.

The metric’s value is compared to the instance’s warning and critical ranges, yielding an appropropiate state depending on how the metric fits in the ranges. Plugin authors may override this method in subclasses to provide custom evaluation logic.

Parameters:
  • metric – metric that is to be evaluated

  • resource – not used

Returns:

Result object

performance(metric: Metric, resource: Resource) Performance[source]

Derives performance data.

The metric’s attributes are combined with the local warning and critical ranges to get a fully populated Performance object.

Parameters:
  • metric – metric from which performance data are derived

  • resource – not used

Returns:

Performance object

mplugin.log: Logger[source]

mplugin integrates with the logging module from Python’s standard library. If the main function is decorated with guarded() (which is heavily recommended), the logging module gets automatically configured before the execution of the main() function starts. Messages logged to the mplugin logger (or any sublogger) are processed with mplugin’s integrated logging.

The verbosity level is set in the check.main() invocation depending on the number of -v flags.

When called with verbose=0, both the summary and the performance data are printed on one line and the warning message is displayed. Messages logged with warning or error level are always printed. Setting verbose to 1 does not change the logging level but enable multi-line output. Additionally, full tracebacks would be printed in the case of an uncaught exception. Verbosity levels of 2 and 3 enable logging with info or debug levels.

class mplugin.Check(*objects: Resource | Context | Summary | Results, name: str | None = None)[source]

Bases: object

Controller logic for check execution.

The class Check orchestrates the the various stages of check execution. Interfacing with the outside system is done via a separate Runtime object.

When a check is called (using Check.main() or Check.__call__()), it probes all resources and evaluates the returned metrics to results and performance data. A typical usage pattern would be to populate a check with domain objects and then delegate control to it.

resources: list[Resource]
contexts: _Contexts
results: Results
perfdata: list[str]
name: str
add(*objects: Resource | Context | Summary | Results)[source]

Adds domain objects to a check.

Parameters:

objects – one or more objects that are descendants from Resource, Context, Summary, or Results.

main(verbose: Any = None, timeout: Any = None, colorize: bool = False) NoReturn[source]

All-in-one control delegation to the runtime environment.

Get a _Runtime instance and perform all phases: run the check (via __call__()), print results and exit the program with an appropriate status code.

Parameters:
  • verbose – output verbosity level between 0 and 3

  • timeout – abort check execution with a Timeout exception after so many seconds (use 0 for no timeout)

  • colorize – Use ANSI colors to colorize the logging output

property state: ServiceState

Overall check state.

The most significant (=worst) state seen in results to far. unknown if no results have been collected yet. Corresponds with exitcode. Read-only property.

property summary: str

Status line summary string.

The first line of output that summarizes that situation as perceived by the check. The string is usually queried from a Summary object. Read-only property.

property verbose: str | list[str] | tuple[str, ...]

Additional lines of output.

Long text output if check runs in verbose mode. Also queried from Summary. Read-only property.

property exitcode: int

Overall check exit code according to the monitoring API.

Corresponds with state. Read-only property.

mplugin.cli

Helper classes and functions to setup the Command Line Interface (cli) of monitoring plugins.

class mplugin.cli.MultiArg(args: list[str] | str, fill: str | None = None, splitchar: str = ',')[source]

Bases: object

A container class for handling multiple arguments that can be indexed and iterated.

This class is designed to be used as a type converter in argparse for arguments that accept comma-separated or otherwise delimited values. It provides convenient access to individual arguments with optional fill values for missing indices.

argp.add_argument(
    "--tw",
    "--ttot-warning",
    metavar="RANGE[,RANGE,...]",
    type=mplugin.MultiArg,
    default="",
)
Parameters:
  • args – The list of parsed argument strings.

  • fill – An optional default value to return for indices beyond the length of the args list. If not provided, the last argument is returned instead, or None if the list is empty.

  • splitchar

args: list[str]

The list of parsed argument strings.

fill: str | None

An optional default value to return for indices beyond the length of the args list. If not provided, the last argument is returned instead, or None if the list is empty.

mplugin.cli.setup_argparser(name: str | None, version: str | None = None, license: str | None = None, repository: str | None = None, copyright: str | None = None, description: str | None = None, epilog: str | None = None, verbose: bool = False) ArgumentParser[source]

Set up and configure an argument parser for a monitoring plugin according the Monitoring Plugin Guidelines.

This function creates a customized argparse.ArgumentParser instance with metadata and formatting suitable for monitoring plugins. It automatically prefixes the plugin name with check_ if not already present.

Parameters:
  • name – The name of the plugin. If provided and doesn’t start with check, it will be prefixed with check_.

  • version – The version number of the plugin. If provided, it will be included in the parser description. In addition, an option -V, --version is provided, which outputs the version number.

  • license – The license type of the plugin. If provided, it will be included in the parser description.

  • repository – The repository URL of the plugin. If provided, it will be included in the parser description.

  • copyright – The copyright information for the plugin. If provided, it will be included in the parser description.

  • description – A detailed description of the plugin’s functionality. If provided, it will be appended to the parser description after a blank line.

  • epilog – Additional information to display after the help message.

  • verbose – Provide a -v, --verbose option. The option can be specified multiple times, e. g. -vvv

Returns:

A configured ArgumentParser instance with RawDescriptionHelpFormatter, 80 character width, and metadata assembled from the provided parameters.

mplugin.persistence

Offers classes to persist the state between check runs.

class mplugin.persistence.Cookie(statefile: str | None = None)[source]

Bases: UserDict[str, Any]

Creates a persistent dict to keep state.

Cookies are used to remember file positions, counters and the like between plugin invocations. It is not intended for substantial amounts of data. Cookies are serialized into JSON and saved to a state file. We prefer a plain text format to allow administrators to inspect and edit its content. See LogTail for an application of cookies to get only new lines of a continuously growing file.

Cookies are locked exclusively so that at most one process at a time has access to it. Changes to the dict are not reflected in the file until Cookie.commit() is called. It is recommended to use Cookie as context manager to get it opened and committed automatically.

After creation, a cookie behaves like a normal dict.

Parameters:

statefile – file name to save the dict’s contents

Note

If statefile is empty or None, the Cookie will be oblivous, i.e., it will forget its contents on garbage collection. This makes it possible to explicitely throw away state between plugin runs (for example by a command line argument).

path: str | None
fobj: TextIOWrapper | None
open() Self[source]

Reads/creates the state file and initializes the dict.

If the state file does not exist, it is touched into existence. An exclusive lock is acquired to ensure serialized access. If open() fails to parse file contents, it truncates the file before raising an exception. This guarantees that plugins will not fail repeatedly when their state files get damaged.

Returns:

Cookie object (self)

Raises:

ValueError – if the state file is corrupted or does not deserialize into a dict

close() None[source]

Closes a cookie and its underlying state file.

This method has no effect if the cookie is already closed. Once the cookie is closed, any operation (like commit()) will raise an exception.

commit() None[source]

Persists the cookie’s dict items in the state file.

The cookies content is serialized as JSON string and saved to the state file. The buffers are flushed to ensure that the new content is saved in a durable way.

class mplugin.persistence.LogTail(path: str, cookie: Cookie)[source]

Bases: object

Access previously unseen parts of a growing file.

LogTail builds on Cookie to access new lines of a continuosly growing log file. It should be used as context manager that provides an iterator over new lines to the subordinate context. LogTail saves the last file position into the provided cookie object. As the path to the log file is saved in the cookie, several LogTail instances may share the same cookie.

path: str
cookie: Cookie
logfile: BufferedIOBase | None
stat: stat_result | None

mplugin.testing

Helper classes and methods for testing monitoring plugins.

class mplugin.testing.MockResult(sys_exit_mock: Mock, stdout: StringIO | None, stderr: StringIO | None)[source]

Bases: object

A class to collect the result of a mocked execution.

property exitcode: int

The captured exit code

property state: ServiceState
property stdout: str | None
property stderr: str | None
property output: str
property first_line: str | None

The first line of the output without a newline break at the end as a string.

mplugin.testing.run_with_bin(args: list[str], bin_dir: Path) CompletedProcess[str][source]

Run a command with a modified PATH environment variable.

Prepends the specified binary directory to the PATH environment variable before running the subprocess, allowing executables in that directory to be found first during command resolution.

Parameters:
  • args – List of command arguments to execute

  • bin_dir – Directory to prepend to the PATH environment variable

Returns:

Completed process object with stdout and stderr as strings

mplugin.timespan

Offers classes and functions to make it easier and more efficient to work with time spans.

mplugin.timespan.convert_timespan_to_sec(spec: str | int | float) float[source]

Convert a timespan format string to seconds. If no time unit is specified, generally seconds are assumed.

The following time units are understood:

  • years, year, y (defined as 365.25 days)

  • months, month, M (defined as 30.44 days)

  • weeks, week, w

  • days, day, d

  • hours, hour, hr, h

  • minutes, minute, min, m

  • seconds, second, sec, s

  • milliseconds, millisecond, msec, ms

  • microseconds, microsecond, usec, μs, μ, us

This function can be used as type in the argparse.ArgumentParser.add_argument() method.

parser.add_argument(
    "-c",
    "--critical",
    default=5356800,
    help="Interval in seconds for critical state.",
    type=timespan,
)
Parameters:

spec – The specification of the timespan as a string, for example 2.345s, 3min 45.234s, 34min, 2 months 8 days or as a number.

Returns:

The timespan in seconds

mplugin.timespan.TIMESPAN_FORMAT_HELP

This string can be included in the Command Line Interface help text.

class mplugin.timespan.Timespan(start: int | float | datetime | None = None, end: int | float | datetime | None = None, timespan_from_now: int | float | None = None)[source]

Bases: object

A class to represent a time interval between two datetime objects.

The Timespan class manages a time period defined by a start and end datetime. It supports multiple ways to initialize the timespan, including explicit start/end times or a duration from the current moment.

Parameters:
  • start – The start datetime. Can be a datetime object, Unix timestamp (int/float), or None to use current time. Default is None.

  • end – The end datetime. Can be a datetime object, Unix timestamp (int/float), or None to use current time. Default is None.

  • timespan_from_now – Duration in seconds from the current moment to define the timespan. If specified, end is set to now and start is calculated backwards. Cannot be used together with start or end parameters. Default is None.

Raises:

ValueError – If both start/end and timespan_from_now parameters are specified.

Examples

Create a timespan from explicit start and end times:

ts = Timespan(start=datetime(2024, 1, 1), end=datetime(2024, 1, 2))

Create a timespan for the last hour:

ts = Timespan(timespan_from_now=3600)

Compare timespans with numeric values:

if ts > 3600:  # more than 1 hour
    print("Long timespan")

Convert to different types:

duration_seconds = float(ts)
duration_rounded = int(ts)
end: datetime

The end of the timespan.

start: datetime

The beginning of the timespan.

property timespan: float

The duration of the timespan in seconds.