timeutils

Time related utilities and helper functions.

class oslo_utils.timeutils.Split(elapsed: float, length: float)

A immutable stopwatch split.

See: http://en.wikipedia.org/wiki/Stopwatch for what this is/represents.

Added in version 1.4.

property elapsed: float

Duration from stopwatch start.

property length: float

Seconds from last split (or the elapsed time if no prior split).

class oslo_utils.timeutils.StopWatch(duration: float | None = None)

A simple timer/stopwatch helper class.

Inspired by: apache-commons-lang java stopwatch.

Not thread-safe (when a single watch is mutated by multiple threads at the same time). Thread-safe when used by a single thread (not shared) or when operations are performed in a thread-safe manner on these objects by wrapping those operations with locks.

Added in version 1.4.

__enter__() StopWatch

Starts the watch.

__exit__(type: Any, value: Any, traceback: Any) None

Stops the watch (ignoring errors if stop fails).

elapsed(maximum: float | None = None) float

Returns how many seconds have elapsed.

expired() bool

Returns if the watch has expired (ie, duration provided elapsed).

has_started() bool

Returns True if the watch is in a started state.

has_stopped() bool

Returns True if the watch is in a stopped state.

leftover(return_none: Literal[False] = False) float
leftover(return_none: Literal[True]) float | None

Returns how many seconds are left until the watch expires.

Parameters:

return_none (boolean) – when True instead of raising a RuntimeError when no duration has been set this call will return None instead.

restart() StopWatch

Restarts the watch from a started/stopped state.

resume() None

Resumes the watch from a stopped state.

split() Split

Captures a split/elapsed since start time (and doesn’t stop).

property splits: tuple[Split, ...]

Accessor to all/any splits that have been captured.

start() StopWatch

Starts the watch (if not already started).

NOTE(harlowja): resets any splits previously captured (if any).

stop() StopWatch | None

Stops the watch.

oslo_utils.timeutils.advance_time_delta(timedelta: timedelta) None

Advance overridden time using a datetime.timedelta.

See oslo_utils.fixture.TimeFixture.

oslo_utils.timeutils.advance_time_seconds(seconds: int | float) None

Advance overridden time by seconds.

See oslo_utils.fixture.TimeFixture.

oslo_utils.timeutils.clear_time_override() None

Remove the overridden time.

See oslo_utils.fixture.TimeFixture.

oslo_utils.timeutils.delta_seconds(before: datetime, after: datetime) float

Return the difference between two timing objects.

Compute the difference in seconds between two date, time, or datetime objects (as a float, to microsecond resolution).

oslo_utils.timeutils.is_newer_than(after: str | datetime, seconds: int | float) bool

Return True if after is newer than seconds.

Changed in version 1.7: Accept datetime string with timezone information. Fix comparison with timezone aware datetime.

oslo_utils.timeutils.is_older_than(before: str | datetime, seconds: int | float) bool

Return True if before is older than seconds.

Changed in version 1.7: Accept datetime string with timezone information. Fix comparison with timezone aware datetime.

oslo_utils.timeutils.is_soon(dt: datetime, window: int | float) bool

Determines if time is going to happen in the next window seconds.

Parameters:
  • dt – the time

  • window – minimum seconds to remain to consider the time not soon

Returns:

True if expiration is within the given duration

oslo_utils.timeutils.marshall_now(now: datetime | None = None) dict[str, Any]

Make an rpc-safe datetime with microseconds.

Changed in version 1.6: Timezone information is now serialized instead of being stripped.

oslo_utils.timeutils.normalize_time(timestamp: datetime) datetime

Normalize time in arbitrary timezone to UTC naive object.

oslo_utils.timeutils.parse_isotime(timestr: str) datetime

Parse time from ISO 8601 format.

Parameters:

timestr – ISO 8601 formatted datetime string

Returns:

A timezone-aware datetime.datetime instance

Raises:

ValueError – When the string cannot be parsed as ISO 8601

Note

For historical reasons, datetime strings without explicit timezone designators (Z, +HH:MM, -HH:MM) are treated as UTC timestamps rather than naive/local time as specified by ISO 8601. This behavior is preserved for backward compatibility.

For ISO 8601 compliant parsing that returns naive datetime objects when no timezone is specified, consider using datetime.datetime.fromisoformat() (Python 3.7+) or the iso8601 library directly with default_timezone=None.

Examples:

>>> # Strings without timezone designators are treated as UTC
>>> parse_isotime('2012-02-14T20:53:07')
datetime.datetime(2012, 2, 14, 20, 53, 7, tzinfo=<UTC>)
>>> # Explicit timezone designators are respected
>>> parse_isotime('2012-02-14T20:53:07Z')
datetime.datetime(2012, 2, 14, 20, 53, 7, tzinfo=<UTC>)
>>> parse_isotime('2012-02-14T20:53:07+05:30')
datetime.datetime(2012, 2, 14, 20, 53, 7, tzinfo=<+05:30>)
oslo_utils.timeutils.parse_strtime(timestr: str, fmt: str = '%Y-%m-%dT%H:%M:%S.%f') datetime

Turn a formatted time back into a datetime.

oslo_utils.timeutils.set_time_override(override_time: datetime | None = None) None

Overrides utils.utcnow.

Make it return a constant time or a list thereof, one at a time.

See oslo_utils.fixture.TimeFixture.

Parameters:

override_time – datetime instance or list thereof. If not given, defaults to the current UTC time.

oslo_utils.timeutils.time_it(logger: Logger, log_level: int = 10, message: str = "It took %(seconds).02f seconds to run function '%(func_name)s'", enabled: bool = True, min_duration: float = 0.01) Callable[[Callable[[...], Any]], Callable[[...], Any]]

Decorator that will log how long its decorated function takes to run.

This does not output a log if the decorated function fails with an exception.

Parameters:
  • logger – logger instance to use when logging elapsed time

  • log_level – logger logging level to use when logging elapsed time

  • message – customized message to use when logging elapsed time, the message may use automatically provide values %(seconds) and %(func_name) if it finds those values useful to record

  • enabled – whether to enable or disable this decorator (useful to decorate a function with this decorator, and then easily be able to switch that decoration off by some config or other value)

  • min_duration – argument that determines if logging is triggered or not, it is by default set to 0.01 seconds to avoid logging when durations and/or elapsed function call times are less than 0.01 seconds, to disable any min_duration checks this value should be set to less than or equal to zero or set to none

oslo_utils.timeutils.unmarshall_time(tyme: dict[str, Any]) datetime

Unmarshall a datetime dict.

Changed in version 1.5: Drop leap second.

Changed in version 1.6: Added support for timezone information.

oslo_utils.timeutils.utcnow_ts(microsecond: bool = False) float

Timestamp version of our utcnow function.

See oslo_utils.fixture.TimeFixture.

Changed in version 1.3: Added optional microsecond parameter.