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.
- timecore/__init__.py +123 -0
- timecore/_internal/__init__.py +1 -0
- timecore/availability/__init__.py +7 -0
- timecore/availability/availability.py +360 -0
- timecore/calendar/__init__.py +13 -0
- timecore/calendar/_common.py +71 -0
- timecore/calendar/business.py +326 -0
- timecore/calendar/calendar.py +92 -0
- timecore/calendar/holidays.py +168 -0
- timecore/clock/__init__.py +14 -0
- timecore/clock/clock.py +138 -0
- timecore/clock/timer.py +142 -0
- timecore/core/__init__.py +26 -0
- timecore/core/_common.py +345 -0
- timecore/core/date.py +257 -0
- timecore/core/duration.py +264 -0
- timecore/core/instant.py +265 -0
- timecore/core/local_datetime.py +347 -0
- timecore/core/period.py +367 -0
- timecore/core/time.py +250 -0
- timecore/core/timezone.py +125 -0
- timecore/core/weekday.py +22 -0
- timecore/core/zoned_datetime.py +442 -0
- timecore/errors.py +48 -0
- timecore/formatting/__init__.py +10 -0
- timecore/formatting/format.py +249 -0
- timecore/interval/__init__.py +8 -0
- timecore/interval/interval.py +478 -0
- timecore/interval/interval_set.py +243 -0
- timecore/parsing/__init__.py +25 -0
- timecore/parsing/parse.py +477 -0
- timecore/py.typed +0 -0
- timecore/recurrence/__init__.py +8 -0
- timecore/recurrence/_shared.py +140 -0
- timecore/recurrence/cron.py +306 -0
- timecore/recurrence/recurrence.py +995 -0
- timecore/schedule/__init__.py +7 -0
- timecore/schedule/schedule.py +519 -0
- timecore-0.1.0.dist-info/METADATA +111 -0
- timecore-0.1.0.dist-info/RECORD +41 -0
- timecore-0.1.0.dist-info/WHEEL +4 -0
timecore/__init__.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""TimeCore: a modern, unified, fully typed Python library for date, time,
|
|
2
|
+
duration, intervals, calendars, recurrence, and scheduling.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
# ruff: noqa: I001 -- imports are grouped by contractual workstream
|
|
6
|
+
# section below, not by isort order (see the `# --- <section> ---` markers).
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
10
|
+
|
|
11
|
+
from .errors import (
|
|
12
|
+
AmbiguousTimeError,
|
|
13
|
+
InvalidIntervalError,
|
|
14
|
+
InvalidLocaleError,
|
|
15
|
+
NonexistentTimeError,
|
|
16
|
+
ParseError,
|
|
17
|
+
TimeCoreError,
|
|
18
|
+
UnknownTimeZoneError,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
__version__ = version("timecore")
|
|
23
|
+
except PackageNotFoundError:
|
|
24
|
+
__version__ = "0.0.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"AmbiguousTimeError",
|
|
28
|
+
"Availability",
|
|
29
|
+
"BusinessCalendar",
|
|
30
|
+
"Calendar",
|
|
31
|
+
"Clock",
|
|
32
|
+
"Cron",
|
|
33
|
+
"Date",
|
|
34
|
+
"DateTime",
|
|
35
|
+
"Duration",
|
|
36
|
+
"FixedClock",
|
|
37
|
+
"HolidayCalendar",
|
|
38
|
+
"Instant",
|
|
39
|
+
"Interval",
|
|
40
|
+
"IntervalSet",
|
|
41
|
+
"InvalidIntervalError",
|
|
42
|
+
"InvalidLocaleError",
|
|
43
|
+
"LocalDateTime",
|
|
44
|
+
"NonexistentTimeError",
|
|
45
|
+
"OffsetClock",
|
|
46
|
+
"ParseError",
|
|
47
|
+
"Period",
|
|
48
|
+
"Recurrence",
|
|
49
|
+
"Schedule",
|
|
50
|
+
"SystemClock",
|
|
51
|
+
"Time",
|
|
52
|
+
"TimeCoreError",
|
|
53
|
+
"TimeZone",
|
|
54
|
+
"Timer",
|
|
55
|
+
"UnknownTimeZoneError",
|
|
56
|
+
"Weekday",
|
|
57
|
+
"__version__",
|
|
58
|
+
"available_timezones",
|
|
59
|
+
"format_duration",
|
|
60
|
+
"format_temporal",
|
|
61
|
+
"parse_date",
|
|
62
|
+
"parse_datetime",
|
|
63
|
+
"parse_duration",
|
|
64
|
+
"parse_instant",
|
|
65
|
+
"parse_local_datetime",
|
|
66
|
+
"parse_natural_language",
|
|
67
|
+
"parse_period",
|
|
68
|
+
"parse_time",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
# --- errors ---
|
|
72
|
+
# (Exports above.)
|
|
73
|
+
|
|
74
|
+
# --- core ---
|
|
75
|
+
# NOTE: the section imports below are in contractual section order, not
|
|
76
|
+
# alphabetical order, so import sorting (I001) is exempted for this block.
|
|
77
|
+
from .core import (
|
|
78
|
+
Date,
|
|
79
|
+
DateTime,
|
|
80
|
+
Duration,
|
|
81
|
+
Instant,
|
|
82
|
+
LocalDateTime,
|
|
83
|
+
Period,
|
|
84
|
+
Time,
|
|
85
|
+
TimeZone,
|
|
86
|
+
Weekday,
|
|
87
|
+
available_timezones,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# --- interval ---
|
|
91
|
+
from .interval import Interval, IntervalSet
|
|
92
|
+
|
|
93
|
+
# --- calendar ---
|
|
94
|
+
# NOTE: kept in its contractual section below the core import; ruff's
|
|
95
|
+
# import sorting would move it above, so the ordering is exempted here.
|
|
96
|
+
from .calendar import BusinessCalendar, Calendar, HolidayCalendar
|
|
97
|
+
|
|
98
|
+
# --- recurrence ---
|
|
99
|
+
from .recurrence import Cron, Recurrence
|
|
100
|
+
|
|
101
|
+
# --- schedule ---
|
|
102
|
+
from .schedule import Schedule
|
|
103
|
+
|
|
104
|
+
# --- availability ---
|
|
105
|
+
from .availability import Availability
|
|
106
|
+
|
|
107
|
+
# --- parsing ---
|
|
108
|
+
from .parsing import (
|
|
109
|
+
parse_date,
|
|
110
|
+
parse_datetime,
|
|
111
|
+
parse_duration,
|
|
112
|
+
parse_instant,
|
|
113
|
+
parse_local_datetime,
|
|
114
|
+
parse_natural_language,
|
|
115
|
+
parse_period,
|
|
116
|
+
parse_time,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# --- formatting ---
|
|
120
|
+
from .formatting import format_duration, format_temporal
|
|
121
|
+
|
|
122
|
+
# --- clock ---
|
|
123
|
+
from .clock import Clock, FixedClock, OffsetClock, SystemClock, Timer
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared private helpers. Not part of the public API."""
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Availability: free/busy intervals, bookable slots, and working hours.
|
|
2
|
+
|
|
3
|
+
An :class:`Availability` answers "when am I free?" for a set of busy
|
|
4
|
+
intervals, optionally restricted to the business days and working
|
|
5
|
+
hours of a :class:`~timecore.calendar.BusinessCalendar`.
|
|
6
|
+
|
|
7
|
+
Everything here is :class:`~timecore.core.DateTime`-based (absolute):
|
|
8
|
+
all inputs and results are ``DateTime`` values, durations are absolute
|
|
9
|
+
:class:`~timecore.core.Duration` values, and no wall-clock arithmetic
|
|
10
|
+
is assumed. A one-hour slot that starts at 01:00 on a DST
|
|
11
|
+
spring-forward day ends at 03:00 (the 02:00 hour does not exist), and
|
|
12
|
+
a free interval spanning a DST transition is one hour shorter or
|
|
13
|
+
longer than its wall-clock span suggests.
|
|
14
|
+
|
|
15
|
+
When a business calendar is given, free time is restricted to the
|
|
16
|
+
half-open working window ``[work_start, work_end)`` on business days;
|
|
17
|
+
weekends and holidays contribute no free time. ``work_start`` /
|
|
18
|
+
``work_end`` override the calendar's hours when provided (each
|
|
19
|
+
independently: giving only ``work_end`` keeps the calendar's
|
|
20
|
+
``work_start``). Without a calendar the defaults are 09:00-17:00, and
|
|
21
|
+
the working-hours restriction does not apply -- free time is any time
|
|
22
|
+
not covered by a busy interval. Business hours are interpreted in the
|
|
23
|
+
time zone of the ``start`` (or ``after`` / ``at``) argument passed to
|
|
24
|
+
each query.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
from collections.abc import Iterable
|
|
30
|
+
from typing import cast
|
|
31
|
+
|
|
32
|
+
from ..calendar import BusinessCalendar
|
|
33
|
+
from ..core import DateTime, Duration, LocalDateTime, Period, Time, TimeZone
|
|
34
|
+
from ..errors import AmbiguousTimeError, NonexistentTimeError
|
|
35
|
+
from ..interval import Interval, IntervalSet
|
|
36
|
+
|
|
37
|
+
__all__ = ["Availability"]
|
|
38
|
+
|
|
39
|
+
#: Default working hours when neither a calendar nor explicit hours
|
|
40
|
+
#: are given.
|
|
41
|
+
_DEFAULT_WORK_START = Time(9)
|
|
42
|
+
_DEFAULT_WORK_END = Time(17)
|
|
43
|
+
|
|
44
|
+
#: How far ahead :meth:`Availability.next_available` searches when no
|
|
45
|
+
#: ``until`` is given.
|
|
46
|
+
_DEFAULT_HORIZON = Duration(days=365)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _at_timezone(local: LocalDateTime, timezone: TimeZone) -> DateTime:
|
|
50
|
+
"""Interpret a wall time in ``timezone``.
|
|
51
|
+
|
|
52
|
+
Ambiguous wall times resolve to the earlier occurrence and
|
|
53
|
+
nonexistent wall times shift forward to the first valid time
|
|
54
|
+
after the gap.
|
|
55
|
+
"""
|
|
56
|
+
try:
|
|
57
|
+
return local.at_timezone(timezone)
|
|
58
|
+
except AmbiguousTimeError:
|
|
59
|
+
return local.at_timezone(timezone, disambiguation="earlier")
|
|
60
|
+
except NonexistentTimeError:
|
|
61
|
+
return local.at_timezone(timezone, disambiguation="later")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _require_datetime(value: object, what: str) -> DateTime:
|
|
65
|
+
"""Return ``value`` if it is a DateTime, else raise."""
|
|
66
|
+
if isinstance(value, DateTime):
|
|
67
|
+
return value
|
|
68
|
+
raise TypeError(f"{what} must be a DateTime, got {type(value).__name__}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _require_duration(value: object, what: str) -> Duration:
|
|
72
|
+
"""Return ``value`` if it is a positive Duration, else raise."""
|
|
73
|
+
if not isinstance(value, Duration):
|
|
74
|
+
raise TypeError(f"{what} must be a Duration, got {type(value).__name__}")
|
|
75
|
+
if value <= Duration.ZERO:
|
|
76
|
+
raise ValueError(f"{what} must be positive, got {value}")
|
|
77
|
+
return value
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _require_time_or_none(value: object, what: str) -> Time | None:
|
|
81
|
+
"""Return ``value`` if it is a Time or None, else raise."""
|
|
82
|
+
if value is None or isinstance(value, Time):
|
|
83
|
+
return value
|
|
84
|
+
raise TypeError(f"{what} must be a Time or None, got {type(value).__name__}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _require_business_calendar_or_none(
|
|
88
|
+
value: object, what: str
|
|
89
|
+
) -> BusinessCalendar | None:
|
|
90
|
+
"""Return ``value`` if it is a BusinessCalendar or None, else raise."""
|
|
91
|
+
if value is None or isinstance(value, BusinessCalendar):
|
|
92
|
+
return value
|
|
93
|
+
raise TypeError(
|
|
94
|
+
f"{what} must be a BusinessCalendar or None, got {type(value).__name__}"
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _normalize_busy(busy: object) -> IntervalSet:
|
|
99
|
+
"""Normalize ``busy`` to an ``IntervalSet`` of ``DateTime`` intervals."""
|
|
100
|
+
if busy is None:
|
|
101
|
+
return IntervalSet()
|
|
102
|
+
if isinstance(busy, IntervalSet):
|
|
103
|
+
for interval in busy.intervals:
|
|
104
|
+
if not isinstance(interval.start, DateTime):
|
|
105
|
+
raise TypeError(
|
|
106
|
+
"Availability busy intervals must have DateTime "
|
|
107
|
+
f"endpoints, got {type(interval.start).__name__}"
|
|
108
|
+
)
|
|
109
|
+
return busy
|
|
110
|
+
if not isinstance(busy, Iterable):
|
|
111
|
+
raise TypeError(
|
|
112
|
+
"busy must be an IntervalSet or an iterable of Interval, "
|
|
113
|
+
f"got {type(busy).__name__}"
|
|
114
|
+
)
|
|
115
|
+
items: Iterable[object] = cast(Iterable[object], busy)
|
|
116
|
+
intervals: list[Interval] = []
|
|
117
|
+
for item in items:
|
|
118
|
+
if not isinstance(item, Interval):
|
|
119
|
+
raise TypeError(
|
|
120
|
+
f"busy must contain Interval values, got {type(item).__name__}"
|
|
121
|
+
)
|
|
122
|
+
if not isinstance(item.start, DateTime):
|
|
123
|
+
raise TypeError(
|
|
124
|
+
"Availability busy intervals must have DateTime "
|
|
125
|
+
f"endpoints, got {type(item.start).__name__}"
|
|
126
|
+
)
|
|
127
|
+
intervals.append(item)
|
|
128
|
+
return IntervalSet(intervals)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class Availability:
|
|
132
|
+
"""Free/busy computation over ``DateTime`` intervals.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
busy: The busy intervals, as an :class:`~timecore.interval.IntervalSet`
|
|
136
|
+
or an iterable of :class:`~timecore.interval.Interval`
|
|
137
|
+
(all with ``DateTime`` endpoints), or ``None`` for no busy
|
|
138
|
+
time.
|
|
139
|
+
business_calendar: A :class:`~timecore.calendar.BusinessCalendar`
|
|
140
|
+
restricting free time to business days and working hours,
|
|
141
|
+
or ``None`` (the default) for no such restriction.
|
|
142
|
+
work_start: The working day's start time, overriding the
|
|
143
|
+
calendar's ``work_start`` when given.
|
|
144
|
+
work_end: The working day's end time, overriding the
|
|
145
|
+
calendar's ``work_end`` when given.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
ValueError: If the effective working hours are empty
|
|
149
|
+
(``work_start`` is not before ``work_end``).
|
|
150
|
+
|
|
151
|
+
Example:
|
|
152
|
+
>>> busy = [Interval(
|
|
153
|
+
... DateTime(2026, 1, 5, 10, 0, timezone="America/New_York"),
|
|
154
|
+
... DateTime(2026, 1, 5, 12, 0, timezone="America/New_York"),
|
|
155
|
+
... )]
|
|
156
|
+
>>> avail = Availability(busy=busy)
|
|
157
|
+
>>> avail.free_intervals(
|
|
158
|
+
... DateTime(2026, 1, 5, 9, 0, timezone="America/New_York"),
|
|
159
|
+
... DateTime(2026, 1, 5, 17, 0, timezone="America/New_York"),
|
|
160
|
+
... )
|
|
161
|
+
IntervalSet([Interval(DateTime(2026, 1, 5, 9, 0, timezone=TimeZone('America/New_York')), DateTime(2026, 1, 5, 10, 0, timezone=TimeZone('America/New_York'))), Interval(DateTime(2026, 1, 5, 12, 0, timezone=TimeZone('America/New_York')), DateTime(2026, 1, 5, 17, 0, timezone=TimeZone('America/New_York')))])
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
__slots__ = ("_business_calendar", "_busy", "_work_end", "_work_start")
|
|
165
|
+
|
|
166
|
+
_busy: IntervalSet
|
|
167
|
+
_business_calendar: BusinessCalendar | None
|
|
168
|
+
_work_start: Time
|
|
169
|
+
_work_end: Time
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
*,
|
|
174
|
+
busy: IntervalSet | Iterable[Interval] | None = None,
|
|
175
|
+
business_calendar: BusinessCalendar | None = None,
|
|
176
|
+
work_start: Time | None = None,
|
|
177
|
+
work_end: Time | None = None,
|
|
178
|
+
) -> None:
|
|
179
|
+
business_calendar = _require_business_calendar_or_none(
|
|
180
|
+
business_calendar, "business_calendar"
|
|
181
|
+
)
|
|
182
|
+
work_start = _require_time_or_none(work_start, "work_start")
|
|
183
|
+
work_end = _require_time_or_none(work_end, "work_end")
|
|
184
|
+
if work_start is None:
|
|
185
|
+
if business_calendar is not None:
|
|
186
|
+
work_start = business_calendar.work_start
|
|
187
|
+
else:
|
|
188
|
+
work_start = _DEFAULT_WORK_START
|
|
189
|
+
if work_end is None:
|
|
190
|
+
if business_calendar is not None:
|
|
191
|
+
work_end = business_calendar.work_end
|
|
192
|
+
else:
|
|
193
|
+
work_end = _DEFAULT_WORK_END
|
|
194
|
+
if work_start >= work_end:
|
|
195
|
+
raise ValueError(
|
|
196
|
+
f"work_start {work_start} must be before work_end {work_end}"
|
|
197
|
+
)
|
|
198
|
+
self._busy = _normalize_busy(busy)
|
|
199
|
+
self._business_calendar = business_calendar
|
|
200
|
+
self._work_start = work_start
|
|
201
|
+
self._work_end = work_end
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def busy(self) -> IntervalSet:
|
|
205
|
+
"""The busy intervals, as an :class:`IntervalSet`."""
|
|
206
|
+
return self._busy
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def business_calendar(self) -> BusinessCalendar | None:
|
|
210
|
+
"""The business calendar restricting free time, or ``None``."""
|
|
211
|
+
return self._business_calendar
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def work_start(self) -> Time:
|
|
215
|
+
"""The effective start of the working day (inclusive)."""
|
|
216
|
+
return self._work_start
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def work_end(self) -> Time:
|
|
220
|
+
"""The effective end of the working day (exclusive)."""
|
|
221
|
+
return self._work_end
|
|
222
|
+
|
|
223
|
+
# -- queries --------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
def free_intervals(self, start: DateTime, end: DateTime) -> IntervalSet:
|
|
226
|
+
"""Return the free time in the half-open range ``[start, end)``.
|
|
227
|
+
|
|
228
|
+
The range minus the busy intervals, further restricted to the
|
|
229
|
+
working window ``[work_start, work_end)`` on business days
|
|
230
|
+
when a business calendar is given. An empty range returns an
|
|
231
|
+
empty set.
|
|
232
|
+
|
|
233
|
+
Raises:
|
|
234
|
+
ValueError: If ``end`` is before ``start``.
|
|
235
|
+
"""
|
|
236
|
+
start = _require_datetime(start, "free_intervals() start")
|
|
237
|
+
end = _require_datetime(end, "free_intervals() end")
|
|
238
|
+
if end < start:
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"free_intervals() end {end} must not be before start {start}"
|
|
241
|
+
)
|
|
242
|
+
if end == start:
|
|
243
|
+
return IntervalSet()
|
|
244
|
+
free = IntervalSet([Interval(start, end)]).difference(self._busy)
|
|
245
|
+
if self._business_calendar is None:
|
|
246
|
+
return free
|
|
247
|
+
calendar = self._business_calendar
|
|
248
|
+
timezone = start.timezone
|
|
249
|
+
first_day = start.date()
|
|
250
|
+
last_day = end.astimezone(timezone).date()
|
|
251
|
+
windows: list[Interval] = []
|
|
252
|
+
day = first_day
|
|
253
|
+
while day <= last_day:
|
|
254
|
+
if calendar.is_business_day(day):
|
|
255
|
+
window_start = _at_timezone(
|
|
256
|
+
day.to_local_datetime(self._work_start), timezone
|
|
257
|
+
)
|
|
258
|
+
window_end = _at_timezone(
|
|
259
|
+
day.to_local_datetime(self._work_end), timezone
|
|
260
|
+
)
|
|
261
|
+
windows.append(Interval(window_start, window_end))
|
|
262
|
+
day = day + Period(days=1)
|
|
263
|
+
return free.intersection(IntervalSet(windows))
|
|
264
|
+
|
|
265
|
+
def slots(
|
|
266
|
+
self,
|
|
267
|
+
start: DateTime,
|
|
268
|
+
end: DateTime,
|
|
269
|
+
duration: Duration,
|
|
270
|
+
*,
|
|
271
|
+
step: Duration | None = None,
|
|
272
|
+
) -> list[Interval]:
|
|
273
|
+
"""Return the bookable slots of exactly ``duration`` in ``[start, end)``.
|
|
274
|
+
|
|
275
|
+
Slots are consecutive within each free interval, starting at
|
|
276
|
+
the interval's start and advancing by ``step`` (which defaults
|
|
277
|
+
to ``duration``, giving back-to-back slots). A trailing
|
|
278
|
+
partial slot -- a remainder shorter than ``duration`` at the
|
|
279
|
+
end of a free interval -- is dropped, never shortened: every
|
|
280
|
+
returned slot lasts exactly ``duration``. Slots may overlap
|
|
281
|
+
when ``step`` is shorter than ``duration`` and leave gaps
|
|
282
|
+
when it is longer.
|
|
283
|
+
"""
|
|
284
|
+
start = _require_datetime(start, "slots() start")
|
|
285
|
+
end = _require_datetime(end, "slots() end")
|
|
286
|
+
duration = _require_duration(duration, "slots() duration")
|
|
287
|
+
step = duration if step is None else _require_duration(step, "slots() step")
|
|
288
|
+
result: list[Interval] = []
|
|
289
|
+
for interval in self.free_intervals(start, end).intervals:
|
|
290
|
+
cursor = interval.start
|
|
291
|
+
finish = interval.end
|
|
292
|
+
if not isinstance(cursor, DateTime) or not isinstance(finish, DateTime):
|
|
293
|
+
# Unreachable: free intervals are always DateTime-based.
|
|
294
|
+
continue
|
|
295
|
+
while cursor + duration <= finish:
|
|
296
|
+
result.append(Interval(cursor, cursor + duration))
|
|
297
|
+
cursor = cursor + step
|
|
298
|
+
return result
|
|
299
|
+
|
|
300
|
+
def next_available(
|
|
301
|
+
self,
|
|
302
|
+
after: DateTime,
|
|
303
|
+
duration: Duration,
|
|
304
|
+
*,
|
|
305
|
+
until: DateTime | None = None,
|
|
306
|
+
) -> Interval | None:
|
|
307
|
+
"""Return the first free slot of ``duration`` starting at or after ``after``.
|
|
308
|
+
|
|
309
|
+
The slot starts at or after ``after`` and ends at or before
|
|
310
|
+
``until`` when ``until`` is given. When ``until`` is ``None``
|
|
311
|
+
the search runs up to one year ahead of ``after``. Returns
|
|
312
|
+
``None`` when no such slot exists in the searched range.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
ValueError: If ``until`` is before ``after``.
|
|
316
|
+
"""
|
|
317
|
+
after = _require_datetime(after, "next_available() after")
|
|
318
|
+
duration = _require_duration(duration, "next_available() duration")
|
|
319
|
+
if until is not None:
|
|
320
|
+
until = _require_datetime(until, "next_available() until")
|
|
321
|
+
if until < after:
|
|
322
|
+
raise ValueError(
|
|
323
|
+
f"next_available() until {until} must not be before after {after}"
|
|
324
|
+
)
|
|
325
|
+
horizon = until if until is not None else after + _DEFAULT_HORIZON
|
|
326
|
+
if horizon <= after:
|
|
327
|
+
return None
|
|
328
|
+
for interval in self.free_intervals(after, horizon).intervals:
|
|
329
|
+
slot_start = interval.start
|
|
330
|
+
slot_end = interval.end
|
|
331
|
+
if not isinstance(slot_start, DateTime) or not isinstance(
|
|
332
|
+
slot_end, DateTime
|
|
333
|
+
):
|
|
334
|
+
# Unreachable: free intervals are always DateTime-based.
|
|
335
|
+
continue
|
|
336
|
+
candidate_end = slot_start + duration
|
|
337
|
+
if candidate_end <= slot_end and (until is None or candidate_end <= until):
|
|
338
|
+
return Interval(slot_start, candidate_end)
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
def is_available(self, at: DateTime, duration: Duration) -> bool:
|
|
342
|
+
"""Return whether the half-open range ``[at, at + duration)`` is entirely free.
|
|
343
|
+
|
|
344
|
+
The range must lie inside free time (and, when a business
|
|
345
|
+
calendar is given, inside working hours on a business day).
|
|
346
|
+
"""
|
|
347
|
+
at = _require_datetime(at, "is_available() at")
|
|
348
|
+
duration = _require_duration(duration, "is_available() duration")
|
|
349
|
+
end = at + duration
|
|
350
|
+
return self.free_intervals(at, end).total_duration() == duration
|
|
351
|
+
|
|
352
|
+
def __repr__(self) -> str:
|
|
353
|
+
parts: list[str] = []
|
|
354
|
+
if not self._busy.is_empty:
|
|
355
|
+
parts.append(f"busy={self._busy!r}")
|
|
356
|
+
if self._business_calendar is not None:
|
|
357
|
+
parts.append(f"business_calendar={self._business_calendar!r}")
|
|
358
|
+
parts.append(f"work_start={self._work_start!r}")
|
|
359
|
+
parts.append(f"work_end={self._work_end!r}")
|
|
360
|
+
return f"Availability({', '.join(parts)})"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Calendars, holidays, and business days."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .business import BusinessCalendar
|
|
6
|
+
from .calendar import Calendar
|
|
7
|
+
from .holidays import HolidayCalendar
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"BusinessCalendar",
|
|
11
|
+
"Calendar",
|
|
12
|
+
"HolidayCalendar",
|
|
13
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Private shared helpers for the calendar workstream.
|
|
2
|
+
|
|
3
|
+
These are small runtime validators and converters used by the calendar
|
|
4
|
+
modules. They are internal to :mod:`timecore.calendar` and are not part
|
|
5
|
+
of the public API.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import TypeVar
|
|
11
|
+
|
|
12
|
+
from ..core import Date, Period, Time
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"_add_days",
|
|
16
|
+
"_require_date",
|
|
17
|
+
"_require_instance",
|
|
18
|
+
"_require_int",
|
|
19
|
+
"_require_str",
|
|
20
|
+
"_time_to_ns",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_T = TypeVar("_T")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _require_str(value: object, what: str) -> str:
|
|
27
|
+
"""Return ``value`` if it is a string, else raise ``TypeError``.
|
|
28
|
+
|
|
29
|
+
Takes ``object`` so pyright does not flag the check as unnecessary
|
|
30
|
+
when the caller already declares a ``str`` parameter; the check
|
|
31
|
+
still protects against wrongly typed callers at runtime.
|
|
32
|
+
"""
|
|
33
|
+
if not isinstance(value, str):
|
|
34
|
+
raise TypeError(f"{what} must be a string, got {type(value).__name__}")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _require_instance(value: object, cls: type[_T], what: str) -> _T:
|
|
39
|
+
"""Return ``value`` if it is an instance of ``cls``, else raise ``TypeError``.
|
|
40
|
+
|
|
41
|
+
Takes ``object`` for the same reason as :func:`_require_str`.
|
|
42
|
+
"""
|
|
43
|
+
if not isinstance(value, cls):
|
|
44
|
+
raise TypeError(f"{what} must be a {cls.__name__}, got {type(value).__name__}")
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _require_int(value: object, what: str) -> int:
|
|
49
|
+
"""Return ``value`` if it is an int (not a bool), else raise ``TypeError``."""
|
|
50
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
51
|
+
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _require_date(value: object, what: str) -> Date:
|
|
56
|
+
"""Return ``value`` if it is a :class:`~timecore.core.Date`, else raise ``TypeError``."""
|
|
57
|
+
if not isinstance(value, Date):
|
|
58
|
+
raise TypeError(f"{what} must be a Date, got {type(value).__name__}")
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _add_days(date: Date, days: int) -> Date:
|
|
63
|
+
"""Return ``date`` shifted by ``days`` calendar days."""
|
|
64
|
+
return date + Period(days=days)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _time_to_ns(time: Time) -> int:
|
|
68
|
+
"""Return the number of nanoseconds since midnight for ``time``."""
|
|
69
|
+
return (
|
|
70
|
+
(time.hour * 60 + time.minute) * 60 + time.second
|
|
71
|
+
) * 1_000_000_000 + time.nanosecond
|