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
Expand source code
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."""
    if arg.tzinfo is None:
        if assumed_tz is None:
            raise EnsureAwareError(
                arg,
                assumed_tz=assumed_tz,
                target_tz=target_tz,
            )

        arg = arg.replace(tzinfo=assumed_tz)

    if target_tz:
        return arg.astimezone(tz=target_tz)

    return arg

Ensure timezone awareness of arg.

def is_aware(arg: datetime.date | datetime.time | datetime.datetime, /) ‑> bool
Expand source code
def is_aware(arg: datetime.date | datetime.time | datetime.datetime, /) -> bool:
    """Determine if arg is timezone aware and return a bool."""
    return not is_naive(arg)

Determine if arg is timezone aware and return a bool.

def is_naive(arg: datetime.date | datetime.time | datetime.datetime, /) ‑> bool
Expand source code
@functools.singledispatch
def is_naive(arg: datetime.date | datetime.time | datetime.datetime, /) -> bool:
    """Determine if arg is timezone naive and return a bool."""
    msg: str = (
        f"expected datetime.date | datetime.time | datetime.datetime, got {arg!r}"
    )
    raise TypeError(msg)

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)
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=}'",
        )

Unable to ensure awareness.

Initialize EnsureAwareError with arguments used in ensure_aware().

Ancestors

  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException
class Period (start: datetime.datetime, end: datetime.datetime)
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)

Datetime period supporting arithmetic operations.

Ancestors

  • collections.abc.Container

Instance variables

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

Return duration of period.

var end : datetime.datetime

The type of the None singleton.

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

Return midpoint of period.

var start : datetime.datetime

The type of the None singleton.