Module peprock.datetime

Date/time and related models, helpers and constants.

Complements the datetime package from the standard library (https://docs.python.org/3/library/datetime.html), adding datetime period models, timezone awareness helpers and timedelta constants.

Sub-modules

peprock.datetime.awareness

Timezone awareness helpers …

peprock.datetime.constants

Timedelta constants …

peprock.datetime.period

Datetime period model …

Functions

def ensure_aware(arg: datetime.datetime, /, *, assumed_tz: datetime.tzinfo | None = None, target_tz: datetime.tzinfo | None = None) ‑> datetime.datetime

Ensure timezone awareness of arg.

def is_aware(arg: datetime.date | datetime.time | datetime.datetime, /) ‑> bool

Determine if arg is timezone aware and return a bool.

def is_naive(arg: datetime.date | datetime.time | datetime.datetime, /) ‑> bool

Determine if arg is timezone naive and return a bool.

Classes

class EnsureAwareError (arg: datetime.datetime, /, *, assumed_tz: datetime.tzinfo | None = None, target_tz: datetime.tzinfo | None = None)

Unable to ensure awareness.

Initialize EnsureAwareError with arguments used in ensure_aware().

Expand source code
class EnsureAwareError(ValueError):
    """Unable to ensure awareness."""

    def __init__(
        self: EnsureAwareError,
        arg: datetime.datetime,
        /,
        *,
        assumed_tz: datetime.tzinfo | None = None,
        target_tz: datetime.tzinfo | None = None,
    ) -> None:
        """Initialize EnsureAwareError with arguments used in ensure_aware()."""
        super().__init__(
            f"Unable to ensure awareness of '{arg!r}' using "
            f"'{assumed_tz=}' and '{target_tz=}'",
        )

Ancestors

  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException
class Period (start: datetime.datetime, end: datetime.datetime)

Datetime period supporting arithmetic operations.

Expand source code
@dataclasses.dataclass(frozen=True)
class Period(
    collections.abc.Container["Period | datetime.datetime"],
):
    """Datetime period supporting arithmetic operations."""

    start: datetime.datetime
    end: datetime.datetime

    @functools.cached_property
    def duration(self: Self) -> datetime.timedelta:
        """Return duration of period."""
        return self.end - self.start

    @functools.cached_property
    def midpoint(self: Self) -> datetime.datetime:
        """Return midpoint of period."""
        return self.start + self.duration / 2

    def __contains__(self: Self, item: object) -> bool:
        """Return True if item is in period."""
        match item:
            case Period():
                # noinspection PyUnresolvedReferences
                return self.start <= item.start and item.end <= self.end
            case datetime.datetime():
                # noinspection PyTypeChecker
                return self.start <= item <= self.end

        msg: str = f"expected peprock.datetime.Period | datetime.datetime, got {item!r}"
        raise TypeError(msg)

Ancestors

  • collections.abc.Container

Class variables

var end : datetime.datetime
var start : datetime.datetime

Instance variables

var duration

Return duration of period.

Expand source code
def __get__(self, instance, owner=None):
    if instance is None:
        return self
    if self.attrname is None:
        raise TypeError(
            "Cannot use cached_property instance without calling __set_name__ on it.")
    try:
        cache = instance.__dict__
    except AttributeError:  # not all objects have __dict__ (e.g. class defines slots)
        msg = (
            f"No '__dict__' attribute on {type(instance).__name__!r} "
            f"instance to cache {self.attrname!r} property."
        )
        raise TypeError(msg) from None
    val = cache.get(self.attrname, _NOT_FOUND)
    if val is _NOT_FOUND:
        val = self.func(instance)
        try:
            cache[self.attrname] = val
        except TypeError:
            msg = (
                f"The '__dict__' attribute on {type(instance).__name__!r} instance "
                f"does not support item assignment for caching {self.attrname!r} property."
            )
            raise TypeError(msg) from None
    return val
var midpoint

Return midpoint of period.

Expand source code
def __get__(self, instance, owner=None):
    if instance is None:
        return self
    if self.attrname is None:
        raise TypeError(
            "Cannot use cached_property instance without calling __set_name__ on it.")
    try:
        cache = instance.__dict__
    except AttributeError:  # not all objects have __dict__ (e.g. class defines slots)
        msg = (
            f"No '__dict__' attribute on {type(instance).__name__!r} "
            f"instance to cache {self.attrname!r} property."
        )
        raise TypeError(msg) from None
    val = cache.get(self.attrname, _NOT_FOUND)
    if val is _NOT_FOUND:
        val = self.func(instance)
        try:
            cache[self.attrname] = val
        except TypeError:
            msg = (
                f"The '__dict__' attribute on {type(instance).__name__!r} instance "
                f"does not support item assignment for caching {self.attrname!r} property."
            )
            raise TypeError(msg) from None
    return val