timecore 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ """Clocks: sources of the current instant.
2
+
3
+ A :class:`Clock` is any object that can answer "what time is it now?"
4
+ as an :class:`~timecore.core.Instant`. Core types accept a clock in
5
+ their ``now()`` / ``today()`` classmethods, so tests (and any code that
6
+ needs deterministic time) can inject one instead of reading the system
7
+ clock:
8
+
9
+ Example:
10
+ >>> from timecore import DateTime, FixedClock, Instant
11
+ >>> clock = FixedClock(Instant.parse("2026-01-15T10:30:00Z"))
12
+ >>> DateTime.now(timezone="UTC", clock=clock)
13
+ DateTime(2026, 1, 15, 10, 30, timezone=TimeZone("UTC"))
14
+
15
+ There is no global mutable state here and no import-time side
16
+ effects: :class:`SystemClock` reads the system time on every call and
17
+ never caches the system time zone.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import time
23
+ from abc import ABC, abstractmethod
24
+
25
+ from ..core._common import _require_instance
26
+ from ..core.duration import Duration
27
+ from ..core.instant import Instant
28
+
29
+ __all__ = ["Clock", "FixedClock", "OffsetClock", "SystemClock"]
30
+
31
+
32
+ class Clock(ABC):
33
+ """Abstract source of the current instant.
34
+
35
+ Subclass this (or implement an object with a ``now() -> Instant``
36
+ method -- core ``now()`` / ``today()`` methods accept any such
37
+ object) to provide a custom time source.
38
+ """
39
+
40
+ __slots__ = ()
41
+
42
+ @abstractmethod
43
+ def now(self) -> Instant:
44
+ """Return the current instant as reported by this clock."""
45
+ raise NotImplementedError
46
+
47
+
48
+ class SystemClock(Clock):
49
+ """A clock that reads the real system time.
50
+
51
+ Every call to :meth:`now` reads ``time.time_ns()`` directly, so
52
+ the clock always reflects the current system time and never caches
53
+ anything at import time.
54
+ """
55
+
56
+ __slots__ = ()
57
+
58
+ def now(self) -> Instant:
59
+ """Return the current system time as an :class:`Instant`."""
60
+ return Instant.from_unix_timestamp_ns(time.time_ns())
61
+
62
+ def __repr__(self) -> str:
63
+ return "SystemClock()"
64
+
65
+
66
+ class FixedClock(Clock):
67
+ """A clock stuck at one instant, moved only by explicit calls.
68
+
69
+ Useful in tests: ``now()`` always returns the same instant until
70
+ :meth:`advance` or :meth:`set` moves it, so time-dependent code
71
+ becomes fully deterministic.
72
+ """
73
+
74
+ __slots__ = ("_instant",)
75
+
76
+ def __init__(self, instant: Instant) -> None:
77
+ """Create a clock fixed at ``instant``."""
78
+ self._instant = _require_instance(instant, Instant, "instant")
79
+
80
+ @property
81
+ def instant(self) -> Instant:
82
+ """The instant this clock currently reports."""
83
+ return self._instant
84
+
85
+ def now(self) -> Instant:
86
+ """Return the fixed instant."""
87
+ return self._instant
88
+
89
+ def advance(self, duration: Duration) -> None:
90
+ """Move the clock forward (or backward, for a negative duration).
91
+
92
+ The stored instant is replaced by ``instant + duration``; the
93
+ previous :class:`Instant` is immutable and is left unchanged.
94
+ """
95
+ self._instant = self._instant + _require_instance(
96
+ duration, Duration, "duration"
97
+ )
98
+
99
+ def set(self, instant: Instant) -> None:
100
+ """Move the clock to ``instant``."""
101
+ self._instant = _require_instance(instant, Instant, "instant")
102
+
103
+ def __repr__(self) -> str:
104
+ return f"FixedClock({self._instant!r})"
105
+
106
+
107
+ class OffsetClock(Clock):
108
+ """A clock that reports another clock's time shifted by an offset.
109
+
110
+ ``OffsetClock(base, offset).now()`` is ``base.now() + offset``.
111
+ The offset may be negative, and clocks may be chained: an
112
+ ``OffsetClock`` wrapping another ``OffsetClock`` shifts by the sum
113
+ of the offsets.
114
+ """
115
+
116
+ __slots__ = ("_base", "_offset")
117
+
118
+ def __init__(self, base: Clock, offset: Duration) -> None:
119
+ """Create a clock reporting ``base.now() + offset``."""
120
+ self._base = _require_instance(base, Clock, "base")
121
+ self._offset = _require_instance(offset, Duration, "offset")
122
+
123
+ @property
124
+ def base(self) -> Clock:
125
+ """The clock this clock shifts."""
126
+ return self._base
127
+
128
+ @property
129
+ def offset(self) -> Duration:
130
+ """The shift applied to the base clock's time."""
131
+ return self._offset
132
+
133
+ def now(self) -> Instant:
134
+ """Return ``base.now() + offset``."""
135
+ return self._base.now() + self._offset
136
+
137
+ def __repr__(self) -> str:
138
+ return f"OffsetClock({self._base!r}, {self._offset!r})"
@@ -0,0 +1,142 @@
1
+ """Timer: measure elapsed time with an injectable monotonic source.
2
+
3
+ A :class:`Timer` measures how much time passes between ``start()``
4
+ and ``stop()`` using a monotonic clock, so wall-clock adjustments
5
+ never affect the result. The monotonic source defaults to
6
+ ``time.monotonic_ns`` and can be replaced with any callable returning
7
+ an integer nanosecond count, which makes timers exactly testable.
8
+
9
+ Semantics (all documented here and covered by tests):
10
+
11
+ * ``stop()`` on a stopped timer does not raise: it returns the total
12
+ elapsed time accumulated so far (zero if the timer never ran).
13
+ * ``start()`` on a running timer is a no-op: it does not restart the
14
+ timer or discard elapsed time.
15
+ * ``elapsed()`` while running includes the time since the last
16
+ ``start()``; after ``stop()`` it is frozen at the stopped total.
17
+ * ``reset()`` clears the accumulated time. If the timer is running,
18
+ timing restarts from the moment of the reset; if it is stopped, it
19
+ stays stopped at zero. A timer is fully reusable after ``reset()``.
20
+ * As a context manager, ``with Timer() as t:`` starts the timer on
21
+ entry and stops it on exit; the elapsed time is available afterwards
22
+ via ``elapsed()`` or the value returned by ``stop()`` (which, on an
23
+ already-stopped timer, returns the same total).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import time
29
+ from collections.abc import Callable
30
+ from types import TracebackType
31
+ from typing import Self
32
+
33
+ from ..core.duration import Duration
34
+
35
+ __all__ = ["Timer"]
36
+
37
+
38
+ class Timer:
39
+ """Measure elapsed time from a monotonic source.
40
+
41
+ Args:
42
+ monotonic_ns: Callable returning the current monotonic time in
43
+ nanoseconds. Defaults to :func:`time.monotonic_ns`.
44
+ start: If true (the default), the timer starts running on
45
+ construction; if false, it starts stopped at zero elapsed.
46
+ """
47
+
48
+ __slots__ = ("_elapsed_ns", "_monotonic_ns", "_running", "_start_ns")
49
+
50
+ def __init__(
51
+ self,
52
+ *,
53
+ monotonic_ns: Callable[[], int] | None = None,
54
+ start: bool = True,
55
+ ) -> None:
56
+ if monotonic_ns is None:
57
+ monotonic_ns = time.monotonic_ns
58
+ if not callable(monotonic_ns):
59
+ raise TypeError(
60
+ "monotonic_ns must be a callable returning nanoseconds, "
61
+ f"got {type(monotonic_ns).__name__}"
62
+ )
63
+ self._monotonic_ns = monotonic_ns
64
+ self._elapsed_ns = 0
65
+ self._start_ns: int | None = None
66
+ self._running = False
67
+ if start:
68
+ self.start()
69
+
70
+ @property
71
+ def is_running(self) -> bool:
72
+ """Whether the timer is currently running."""
73
+ return self._running
74
+
75
+ def start(self) -> None:
76
+ """Start (or resume) the timer.
77
+
78
+ A no-op if the timer is already running: elapsed time is kept
79
+ and the start point is not moved.
80
+ """
81
+ if self._running:
82
+ return
83
+ self._start_ns = self._monotonic_ns()
84
+ self._running = True
85
+
86
+ def stop(self) -> Duration:
87
+ """Stop the timer and return the total elapsed time.
88
+
89
+ Stopping an already-stopped timer does not raise; it returns
90
+ the total elapsed time accumulated so far.
91
+ """
92
+ if self._running:
93
+ assert self._start_ns is not None
94
+ self._elapsed_ns += self._monotonic_ns() - self._start_ns
95
+ self._start_ns = None
96
+ self._running = False
97
+ return Duration(nanoseconds=self._elapsed_ns)
98
+
99
+ def reset(self) -> None:
100
+ """Clear the accumulated elapsed time.
101
+
102
+ If the timer is running, timing restarts from now; if it is
103
+ stopped, it stays stopped at zero. The timer is reusable after
104
+ a reset.
105
+ """
106
+ self._elapsed_ns = 0
107
+ if self._running:
108
+ self._start_ns = self._monotonic_ns()
109
+ else:
110
+ self._start_ns = None
111
+
112
+ def elapsed(self) -> Duration:
113
+ """Return the total elapsed time so far.
114
+
115
+ While running, this includes the time since the last
116
+ :meth:`start` (or :meth:`reset`); after :meth:`stop` it is the
117
+ frozen total at the moment of stopping.
118
+ """
119
+ if self._running:
120
+ assert self._start_ns is not None
121
+ return Duration(
122
+ nanoseconds=self._elapsed_ns + (self._monotonic_ns() - self._start_ns)
123
+ )
124
+ return Duration(nanoseconds=self._elapsed_ns)
125
+
126
+ def __enter__(self) -> Self:
127
+ """Start the timer and return it."""
128
+ self.start()
129
+ return self
130
+
131
+ def __exit__(
132
+ self,
133
+ exc_type: type[BaseException] | None,
134
+ exc: BaseException | None,
135
+ traceback: TracebackType | None,
136
+ ) -> bool:
137
+ """Stop the timer; exceptions propagate unchanged."""
138
+ self.stop()
139
+ return False
140
+
141
+ def __repr__(self) -> str:
142
+ return f"Timer(elapsed={self.elapsed()!r}, running={self._running})"
@@ -0,0 +1,26 @@
1
+ """Core temporal types: dates, times, datetimes, instants, durations, and periods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .date import Date
6
+ from .duration import Duration
7
+ from .instant import Instant
8
+ from .local_datetime import LocalDateTime
9
+ from .period import Period
10
+ from .time import Time
11
+ from .timezone import TimeZone, available_timezones
12
+ from .weekday import Weekday
13
+ from .zoned_datetime import DateTime
14
+
15
+ __all__ = [
16
+ "Date",
17
+ "DateTime",
18
+ "Duration",
19
+ "Instant",
20
+ "LocalDateTime",
21
+ "Period",
22
+ "Time",
23
+ "TimeZone",
24
+ "Weekday",
25
+ "available_timezones",
26
+ ]
@@ -0,0 +1,345 @@
1
+ """Private shared helpers for the core workstream.
2
+
3
+ This module is internal to :mod:`timecore.core` and is not part of the
4
+ public API. It holds the small pieces every core type needs: mapping
5
+ ``whenever`` exceptions to TimeCore errors, resolving ``timezone`` /
6
+ ``clock`` arguments, the lazy ``format()`` delegation, runtime type
7
+ validation, and nanosecond decomposition for exact-unit arithmetic.
8
+
9
+ Two notes on cross-workstream integration:
10
+
11
+ * The ``Clock`` name below is the real ``timecore.clock.Clock`` ABC
12
+ for type checking (``if TYPE_CHECKING`` import). At runtime it is
13
+ a structural protocol with the same ``now() -> Instant`` shape, so
14
+ core modules can import the name without a runtime import cycle
15
+ (``timecore.clock`` imports core types). Core ``now()`` /
16
+ ``today()`` methods only ever call ``clock.now()`` and validate its
17
+ return value, never ``isinstance``-check the clock, so the runtime
18
+ protocol and the real ABC are interchangeable here; the public
19
+ ``timecore.Clock`` export is the real ABC.
20
+ * ``_format_value`` lazily imports ``timecore.formatting.format`` so
21
+ core never imports the formatting workstream at module load time.
22
+ The default ``format()`` call returns Babel's ``"medium"`` style
23
+ output; an invalid ``style`` raises ``ValueError``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from collections.abc import Generator
29
+ from contextlib import contextmanager
30
+ from datetime import datetime as _StdDateTime
31
+ from typing import TYPE_CHECKING, Literal, Protocol, TypeVar
32
+
33
+ import whenever
34
+
35
+ from ..errors import (
36
+ AmbiguousTimeError,
37
+ NonexistentTimeError,
38
+ ParseError,
39
+ UnknownTimeZoneError,
40
+ )
41
+
42
+ if TYPE_CHECKING:
43
+ from timecore.clock import Clock
44
+
45
+ from .date import Date
46
+ from .duration import Duration
47
+ from .instant import Instant
48
+ from .local_datetime import LocalDateTime
49
+ from .time import Time
50
+ from .timezone import TimeZone
51
+ from .zoned_datetime import DateTime
52
+ else:
53
+ # Runtime fallback for ``Clock``: a structural protocol matching
54
+ # the real ABC exactly (see the module docstring). Core modules
55
+ # import this name at runtime, so it must exist without importing
56
+ # ``timecore.clock`` (which would be a runtime import cycle, since
57
+ # the clock module imports core types).
58
+ class Clock(Protocol):
59
+ """Structural form of ``timecore.clock.Clock`` (see module docstring).
60
+
61
+ A clock exposes a single method, ``now()``, returning the
62
+ current moment as a :class:`~timecore.core.Instant`. The real
63
+ ``Clock`` ABC satisfies this protocol structurally.
64
+ """
65
+
66
+ def now(self) -> Instant: ...
67
+
68
+
69
+ __all__ = [
70
+ "Clock",
71
+ "Disambiguation",
72
+ "_check_us_precision",
73
+ "_date_today",
74
+ "_exact_parts",
75
+ "_format_value",
76
+ "_instant_from_clock",
77
+ "_instant_to_zoned",
78
+ "_map_parse_errors",
79
+ "_map_whenever_errors",
80
+ "_now_instant",
81
+ "_plain_assume_tz",
82
+ "_require_instance",
83
+ "_require_int",
84
+ "_require_number",
85
+ "_require_str",
86
+ "_require_whole_days",
87
+ "_resolve_timezone",
88
+ "_resolve_timezone_required",
89
+ "_split_subsecond",
90
+ "_strptime",
91
+ "_validate_disambiguation",
92
+ "_zoned_to_tz",
93
+ ]
94
+
95
+ #: Valid ``style`` values for :meth:`format` methods.
96
+ _FORMAT_STYLES = ("short", "medium", "long", "full")
97
+
98
+ #: How to resolve a repeated or skipped local time.
99
+ Disambiguation = Literal["raise", "earlier", "later"]
100
+
101
+ #: Nanoseconds in one day (exact, 24 hours).
102
+ _NS_PER_DAY = 86_400_000_000_000
103
+
104
+ _T = TypeVar("_T")
105
+
106
+
107
+ @contextmanager
108
+ def _map_whenever_errors() -> Generator[None, None, None]:
109
+ """Map whenever's DST / time-zone errors to TimeCore errors.
110
+
111
+ Plain ``ValueError`` / ``TypeError`` from whenever (e.g. an invalid
112
+ date such as February 30) pass through unchanged: they are already
113
+ standard-library exception types, and the contract only requires
114
+ wrapping whenever-specific exception types.
115
+ """
116
+ try:
117
+ yield
118
+ except whenever.RepeatedTime as exc:
119
+ raise AmbiguousTimeError(str(exc)) from exc
120
+ except whenever.SkippedTime as exc:
121
+ raise NonexistentTimeError(str(exc)) from exc
122
+ except whenever.TimeZoneNotFoundError as exc:
123
+ raise UnknownTimeZoneError(str(exc)) from exc
124
+
125
+
126
+ @contextmanager
127
+ def _map_parse_errors() -> Generator[None, None, None]:
128
+ """Like :func:`_map_whenever_errors`, but also maps ``ValueError`` to ``ParseError``.
129
+
130
+ Use this inside ``parse()`` methods, where every failure to interpret
131
+ the input string is a parse error. Time-zone errors keep their more
132
+ specific mapping (``UnknownTimeZoneError``) by being caught first.
133
+ """
134
+ try:
135
+ yield
136
+ except whenever.RepeatedTime as exc:
137
+ raise AmbiguousTimeError(str(exc)) from exc
138
+ except whenever.SkippedTime as exc:
139
+ raise NonexistentTimeError(str(exc)) from exc
140
+ except whenever.TimeZoneNotFoundError as exc:
141
+ raise UnknownTimeZoneError(str(exc)) from exc
142
+ except whenever.InvalidOffsetError as exc:
143
+ raise ParseError(str(exc)) from exc
144
+ except ValueError as exc:
145
+ raise ParseError(str(exc)) from exc
146
+
147
+
148
+ def _validate_disambiguation(value: str) -> Disambiguation:
149
+ """Validate a ``disambiguation`` argument, returning it unchanged."""
150
+ if value not in ("raise", "earlier", "later"):
151
+ raise ValueError(
152
+ f"disambiguation must be one of 'raise', 'earlier', 'later', got {value!r}"
153
+ )
154
+ return value
155
+
156
+
157
+ def _require_str(value: object, what: str) -> str:
158
+ """Return ``value`` if it is a string, else raise ``TypeError``.
159
+
160
+ Takes ``object`` so pyright does not flag the check as unnecessary
161
+ when the caller already declares a ``str`` parameter; the check
162
+ still protects against wrongly typed callers at runtime.
163
+ """
164
+ if not isinstance(value, str):
165
+ raise TypeError(f"{what} must be a string, got {type(value).__name__}")
166
+ return value
167
+
168
+
169
+ def _require_int(value: object, what: str) -> int:
170
+ """Return ``value`` if it is an int (not a bool), else raise ``TypeError``."""
171
+ if isinstance(value, bool) or not isinstance(value, int):
172
+ raise TypeError(f"{what} must be an int, got {type(value).__name__}")
173
+ return value
174
+
175
+
176
+ def _require_number(value: object, what: str) -> int | float:
177
+ """Return ``value`` if it is an int or float (not a bool), else raise ``TypeError``."""
178
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
179
+ raise TypeError(f"{what} must be an int or float, got {type(value).__name__}")
180
+ return value
181
+
182
+
183
+ def _require_instance(value: object, cls: type[_T], what: str) -> _T:
184
+ """Return ``value`` if it is an instance of ``cls``, else raise ``TypeError``."""
185
+ if not isinstance(value, cls):
186
+ raise TypeError(f"{what} must be a {cls.__name__}, got {type(value).__name__}")
187
+ return value
188
+
189
+
190
+ def _resolve_timezone(timezone: TimeZone | str | None) -> TimeZone:
191
+ """Resolve a ``timezone`` argument: ``None`` means the local zone."""
192
+ from .timezone import TimeZone
193
+
194
+ if timezone is None:
195
+ return TimeZone.local()
196
+ if isinstance(timezone, str):
197
+ return TimeZone(timezone)
198
+ return _require_instance(timezone, TimeZone, "timezone")
199
+
200
+
201
+ def _resolve_timezone_required(timezone: TimeZone | str | None) -> TimeZone:
202
+ """Resolve a ``timezone`` argument that must be given explicitly."""
203
+ if timezone is None:
204
+ raise TypeError("a timezone is required here")
205
+ return _resolve_timezone(timezone)
206
+
207
+
208
+ def _instant_from_clock(clock: Clock | None) -> Instant | None:
209
+ """Return the instant from an injectable clock, or ``None`` if no clock was given."""
210
+ if clock is None:
211
+ return None
212
+ from .instant import Instant
213
+
214
+ return _require_instance(clock.now(), Instant, "clock.now()")
215
+
216
+
217
+ def _now_instant(clock: Clock | None) -> Instant:
218
+ """Return the current instant, from ``clock`` when given, else the system clock."""
219
+ from .instant import Instant
220
+
221
+ instant = _instant_from_clock(clock)
222
+ if instant is not None:
223
+ return instant
224
+ with _map_whenever_errors():
225
+ return Instant.from_whenever(whenever.Instant.now())
226
+
227
+
228
+ def _strptime(text: str, fmt: str) -> _StdDateTime:
229
+ """Parse ``text`` with a ``strftime`` pattern, raising ``ParseError`` on failure."""
230
+ try:
231
+ return _StdDateTime.strptime(text, fmt)
232
+ except ValueError as exc:
233
+ raise ParseError(
234
+ f"could not parse {text!r} with format {fmt!r}: {exc}"
235
+ ) from exc
236
+
237
+
238
+ def _format_value(
239
+ value: Date | Time | LocalDateTime | DateTime | Instant,
240
+ *,
241
+ style: str = "medium",
242
+ locale: str | None = None,
243
+ pattern: str | None = None,
244
+ timezone: TimeZone | str | None = None,
245
+ ) -> str:
246
+ """Implement the ``format()`` methods shared by all core types.
247
+
248
+ Delegates lazily to ``timecore.formatting.format_temporal`` so core
249
+ never imports the formatting workstream at module load time. The
250
+ default call returns Babel's ``"medium"`` style output; an invalid
251
+ ``style`` raises ``ValueError``.
252
+ """
253
+ if style not in _FORMAT_STYLES:
254
+ raise ValueError(
255
+ f"style must be one of 'short', 'medium', 'long', 'full', got {style!r}"
256
+ )
257
+ if locale is not None:
258
+ locale = _require_str(locale, "locale")
259
+ if pattern is not None:
260
+ pattern = _require_str(pattern, "pattern")
261
+ from timecore.formatting.format import format_temporal
262
+
263
+ return format_temporal(
264
+ value, style=style, locale=locale, pattern=pattern, timezone=timezone
265
+ )
266
+
267
+
268
+ def _exact_parts(total_ns: int) -> tuple[int, int, int, int, int, int]:
269
+ """Split a nanosecond count into exact-unit parts for whenever ``add()``.
270
+
271
+ Returns ``(hours, minutes, seconds, milliseconds, microseconds,
272
+ nanoseconds)``. Days and weeks are deliberately expressed as hours
273
+ here: in whenever, passing a day-based delta to ``add()`` treats
274
+ days as exact 24-hour periods and emits a
275
+ ``DaysAssumed24HoursWarning``. A ``Duration`` is defined as exact
276
+ time, so hours are the faithful representation and no warning is
277
+ produced.
278
+ """
279
+ sign = -1 if total_ns < 0 else 1
280
+ remaining = abs(total_ns)
281
+ hours, remaining = divmod(remaining, 3_600_000_000_000)
282
+ minutes, remaining = divmod(remaining, 60_000_000_000)
283
+ seconds, remaining = divmod(remaining, 1_000_000_000)
284
+ milliseconds, remaining = divmod(remaining, 1_000_000)
285
+ microseconds, nanoseconds = divmod(remaining, 1_000)
286
+ return (
287
+ sign * hours,
288
+ sign * minutes,
289
+ sign * seconds,
290
+ sign * milliseconds,
291
+ sign * microseconds,
292
+ sign * nanoseconds,
293
+ )
294
+
295
+
296
+ def _split_subsecond(total_ns: int) -> tuple[int, int, int]:
297
+ """Split a sub-second nanosecond count into (milliseconds, microseconds, nanoseconds)."""
298
+ sign = -1 if total_ns < 0 else 1
299
+ remaining = abs(total_ns)
300
+ milliseconds, remaining = divmod(remaining, 1_000_000)
301
+ microseconds, nanoseconds = divmod(remaining, 1_000)
302
+ return sign * milliseconds, sign * microseconds, sign * nanoseconds
303
+
304
+
305
+ def _require_whole_days(duration: Duration) -> int:
306
+ """Return ``duration`` as a whole number of days, else raise ``ValueError``."""
307
+ total_ns = duration.total_nanoseconds()
308
+ if total_ns % _NS_PER_DAY:
309
+ raise ValueError(
310
+ "Date arithmetic with a Duration requires a whole number of days; "
311
+ f"got {duration}"
312
+ )
313
+ return total_ns // _NS_PER_DAY
314
+
315
+
316
+ def _check_us_precision(total_ns: int, what: str) -> None:
317
+ """Raise ``ValueError`` if ``total_ns`` has a sub-microsecond remainder."""
318
+ if total_ns % 1_000:
319
+ raise ValueError(
320
+ f"{what} has sub-microsecond precision and cannot be converted "
321
+ "to a standard-library value without precision loss"
322
+ )
323
+
324
+
325
+ # --- Thin wrappers around whenever calls whose stubs pyright cannot fully
326
+ # resolve. whenever types several time-zone parameters as ``str | SYSTEM_TZ``,
327
+ # and ``SYSTEM_TZ`` is an unresolvable sentinel in its stubs, so the method
328
+ # type is "partially unknown" at every call site. Each wrapper below confines
329
+ # the ignore to one line; the runtime behaviour is unchanged.
330
+ def _date_today(key: str) -> whenever.Date:
331
+ return whenever.Date.today(key) # pyright: ignore[reportUnknownMemberType]
332
+
333
+
334
+ def _instant_to_zoned(inner: whenever.Instant, key: str) -> whenever.ZonedDateTime:
335
+ return inner.to_tz(key) # pyright: ignore[reportUnknownMemberType]
336
+
337
+
338
+ def _zoned_to_tz(inner: whenever.ZonedDateTime, key: str) -> whenever.ZonedDateTime:
339
+ return inner.to_tz(key) # pyright: ignore[reportUnknownMemberType]
340
+
341
+
342
+ def _plain_assume_tz(
343
+ inner: whenever.PlainDateTime, key: str, disambiguation: Disambiguation
344
+ ) -> whenever.ZonedDateTime:
345
+ return inner.assume_tz(key, disambiguation=disambiguation) # pyright: ignore[reportUnknownMemberType]