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
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Cron expressions: schedules such as ``"0 9 * * MON-FRI"``.
|
|
2
|
+
|
|
3
|
+
A :class:`Cron` schedule is absolute (a time of day, not a pattern
|
|
4
|
+
anchored at a start), so :meth:`Cron.next` and
|
|
5
|
+
:meth:`Cron.previous` do not depend on any anchor other than the
|
|
6
|
+
moment passed in. The result type follows the input type:
|
|
7
|
+
``LocalDateTime`` in, ``LocalDateTime`` out; ``DateTime`` in,
|
|
8
|
+
``DateTime`` out.
|
|
9
|
+
|
|
10
|
+
Backed internally by ``croniter``; ``croniter`` types and exceptions
|
|
11
|
+
never leak into the public API.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from datetime import datetime as _StdDateTime
|
|
17
|
+
|
|
18
|
+
from croniter import croniter as _Croniter
|
|
19
|
+
|
|
20
|
+
from ..core import DateTime, LocalDateTime, TimeZone
|
|
21
|
+
from ..errors import ParseError
|
|
22
|
+
from ._shared import _require_str, _resolve_timezone, _to_stdlib
|
|
23
|
+
|
|
24
|
+
__all__ = ["Cron"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _require_int(value: object, what: str) -> int:
|
|
28
|
+
"""Return ``value`` if it is an int (not a bool), else raise ``TypeError``."""
|
|
29
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
30
|
+
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Cron:
|
|
35
|
+
"""A cron schedule, e.g. ``"0 9 * * MON-FRI"`` (09:00 on weekdays).
|
|
36
|
+
|
|
37
|
+
Supports standard 5-field expressions (minute, hour, day of
|
|
38
|
+
month, month, day of week) and 6-field expressions with a leading
|
|
39
|
+
seconds field (``"30 0 9 * * *"`` fires at 09:00:30). Other field
|
|
40
|
+
counts (including 7-field year expressions) raise
|
|
41
|
+
:class:`~timecore.errors.ParseError`. Field values follow cron
|
|
42
|
+
conventions: names (``MON``, ``JAN``), ranges (``1-5``), steps
|
|
43
|
+
(``*/15``), and lists (``1,15``) are accepted.
|
|
44
|
+
|
|
45
|
+
``timezone`` (a :class:`~timecore.core.TimeZone` or a zone key)
|
|
46
|
+
fixes how naive ``LocalDateTime`` inputs are interpreted: their
|
|
47
|
+
wall time is read in that zone. ``DateTime`` inputs keep their own
|
|
48
|
+
zone; ``timezone`` does not re-zone them.
|
|
49
|
+
|
|
50
|
+
DST behaviour: a scheduled wall time that does not exist (DST
|
|
51
|
+
spring-forward) is shifted forward by ``croniter`` to the first
|
|
52
|
+
valid time after the gap (e.g. 02:30 becomes 03:00); a scheduled
|
|
53
|
+
wall time that is ambiguous (DST fall-back) fires on the earlier
|
|
54
|
+
occurrence. ``matches()`` compares at the expression's precision:
|
|
55
|
+
a 5-field expression matches any second within the minute.
|
|
56
|
+
|
|
57
|
+
Example:
|
|
58
|
+
>>> cron = Cron("0 9 * * MON-FRI")
|
|
59
|
+
>>> cron.next(LocalDateTime(2026, 1, 3, 12, 0)) # a Saturday
|
|
60
|
+
LocalDateTime(2026, 1, 5, 9, 0)
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
__slots__ = ("_expression", "_seconds", "_timezone")
|
|
64
|
+
|
|
65
|
+
_expression: str
|
|
66
|
+
_seconds: bool
|
|
67
|
+
_timezone: TimeZone | None
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self, expression: str, *, timezone: TimeZone | str | None = None
|
|
71
|
+
) -> None:
|
|
72
|
+
expression = _require_str(expression, "Cron() expression")
|
|
73
|
+
normalized = " ".join(expression.split())
|
|
74
|
+
if not normalized:
|
|
75
|
+
raise ParseError("cannot parse an empty cron expression")
|
|
76
|
+
fields = normalized.split(" ")
|
|
77
|
+
if len(fields) not in (5, 6):
|
|
78
|
+
raise ParseError(
|
|
79
|
+
"a cron expression must have 5 fields "
|
|
80
|
+
"(minute hour day-of-month month day-of-week) or 6 fields "
|
|
81
|
+
f"with a leading seconds field; got {len(fields)} in "
|
|
82
|
+
f"{expression!r}"
|
|
83
|
+
)
|
|
84
|
+
self._seconds = len(fields) == 6
|
|
85
|
+
self._timezone = _resolve_timezone(timezone, "Cron() timezone")
|
|
86
|
+
self._expression = normalized
|
|
87
|
+
# Validate now, so an invalid expression fails at construction
|
|
88
|
+
# rather than at the first query. Construction alone checks
|
|
89
|
+
# field ranges; whether the schedule can ever fire (e.g.
|
|
90
|
+
# February 30) is a query-time question -- next() returns None
|
|
91
|
+
# for such schedules.
|
|
92
|
+
try:
|
|
93
|
+
_Croniter(
|
|
94
|
+
normalized,
|
|
95
|
+
_StdDateTime(2026, 1, 1, 0, 0),
|
|
96
|
+
ret_type=_StdDateTime,
|
|
97
|
+
second_at_beginning=self._seconds,
|
|
98
|
+
)
|
|
99
|
+
except (ValueError, TypeError) as exc:
|
|
100
|
+
# croniter's CroniterError subclasses ValueError, so this
|
|
101
|
+
# covers every croniter validation failure.
|
|
102
|
+
raise ParseError(f"invalid cron expression {expression!r}: {exc}") from exc
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def is_valid(cls, expression: str) -> bool:
|
|
106
|
+
"""Return whether ``expression`` is a valid cron expression.
|
|
107
|
+
|
|
108
|
+
Returns ``False`` for non-strings and for anything the
|
|
109
|
+
constructor would reject; it never raises.
|
|
110
|
+
"""
|
|
111
|
+
try:
|
|
112
|
+
cls(expression)
|
|
113
|
+
except (ValueError, TypeError):
|
|
114
|
+
# The constructor only raises ParseError (a ValueError),
|
|
115
|
+
# TypeError, or UnknownTimeZoneError (a ValueError).
|
|
116
|
+
return False
|
|
117
|
+
return True
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def expression(self) -> str:
|
|
121
|
+
"""The cron expression, with whitespace normalized."""
|
|
122
|
+
return self._expression
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def timezone(self) -> TimeZone | None:
|
|
126
|
+
"""The time zone naive inputs are read in, or ``None``."""
|
|
127
|
+
return self._timezone
|
|
128
|
+
|
|
129
|
+
def next(self, after: LocalDateTime | DateTime) -> LocalDateTime | DateTime | None:
|
|
130
|
+
"""Return the next scheduled moment strictly after ``after``.
|
|
131
|
+
|
|
132
|
+
Returns ``None`` when no next occurrence can be found (for
|
|
133
|
+
example, a schedule that can never fire, such as February 30).
|
|
134
|
+
"""
|
|
135
|
+
after = self._require_moment(after, "next() after")
|
|
136
|
+
iterator = self._iterator(after)
|
|
137
|
+
try:
|
|
138
|
+
raw = iterator.get_next(_StdDateTime)
|
|
139
|
+
except (ValueError, OverflowError):
|
|
140
|
+
# croniter raises CroniterBadDateError (a ValueError) when
|
|
141
|
+
# no next date can be found within its search horizon.
|
|
142
|
+
return None
|
|
143
|
+
return self._convert(raw, after)
|
|
144
|
+
|
|
145
|
+
def previous(
|
|
146
|
+
self, before: LocalDateTime | DateTime
|
|
147
|
+
) -> LocalDateTime | DateTime | None:
|
|
148
|
+
"""Return the previous scheduled moment strictly before ``before``.
|
|
149
|
+
|
|
150
|
+
Returns ``None`` when no earlier occurrence can be found.
|
|
151
|
+
"""
|
|
152
|
+
before = self._require_moment(before, "previous() before")
|
|
153
|
+
iterator = self._iterator(before)
|
|
154
|
+
try:
|
|
155
|
+
raw = iterator.get_prev(_StdDateTime)
|
|
156
|
+
except (ValueError, OverflowError):
|
|
157
|
+
# As in next(): no earlier date can be found.
|
|
158
|
+
return None
|
|
159
|
+
return self._convert(raw, before)
|
|
160
|
+
|
|
161
|
+
def occurrences(
|
|
162
|
+
self, start: LocalDateTime | DateTime, count: int
|
|
163
|
+
) -> list[LocalDateTime | DateTime]:
|
|
164
|
+
"""Return ``count`` scheduled moments starting at ``start``.
|
|
165
|
+
|
|
166
|
+
``start`` itself is included when it matches the schedule.
|
|
167
|
+
"""
|
|
168
|
+
start = self._require_moment(start, "occurrences() start")
|
|
169
|
+
count = _require_int(count, "occurrences() count")
|
|
170
|
+
if count < 1:
|
|
171
|
+
raise ValueError(f"occurrences() count must be >= 1, got {count}")
|
|
172
|
+
results: list[LocalDateTime | DateTime] = []
|
|
173
|
+
cursor: LocalDateTime | DateTime = start
|
|
174
|
+
if self.matches(start):
|
|
175
|
+
results.append(start)
|
|
176
|
+
while len(results) < count:
|
|
177
|
+
nxt = self.next(cursor)
|
|
178
|
+
if nxt is None:
|
|
179
|
+
break
|
|
180
|
+
results.append(nxt)
|
|
181
|
+
cursor = nxt
|
|
182
|
+
return results
|
|
183
|
+
|
|
184
|
+
def between(
|
|
185
|
+
self,
|
|
186
|
+
start: LocalDateTime | DateTime,
|
|
187
|
+
end: LocalDateTime | DateTime,
|
|
188
|
+
) -> list[LocalDateTime | DateTime]:
|
|
189
|
+
"""Return scheduled moments in the half-open interval ``[start, end)``.
|
|
190
|
+
|
|
191
|
+
Raises ``ValueError`` when ``end`` is before ``start``; a
|
|
192
|
+
``start`` equal to ``end`` is an empty interval.
|
|
193
|
+
"""
|
|
194
|
+
start = self._require_moment(start, "between() start")
|
|
195
|
+
end = self._require_moment(end, "between() end")
|
|
196
|
+
if type(start) is not type(end):
|
|
197
|
+
raise TypeError(
|
|
198
|
+
"between() start and end must be the same type, got "
|
|
199
|
+
f"{type(start).__name__} and {type(end).__name__}"
|
|
200
|
+
)
|
|
201
|
+
if end < start:
|
|
202
|
+
raise ValueError("between() end must not be before start")
|
|
203
|
+
if end == start:
|
|
204
|
+
return []
|
|
205
|
+
results: list[LocalDateTime | DateTime] = []
|
|
206
|
+
if self.matches(start):
|
|
207
|
+
results.append(start)
|
|
208
|
+
cursor = self.next(start)
|
|
209
|
+
while cursor is not None and cursor < end:
|
|
210
|
+
results.append(cursor)
|
|
211
|
+
cursor = self.next(cursor)
|
|
212
|
+
return results
|
|
213
|
+
|
|
214
|
+
def matches(self, moment: LocalDateTime | DateTime) -> bool:
|
|
215
|
+
"""Return whether ``moment`` matches this schedule.
|
|
216
|
+
|
|
217
|
+
A 5-field expression compares at minute precision (any second
|
|
218
|
+
within a matching minute matches); a 6-field expression
|
|
219
|
+
compares at second precision.
|
|
220
|
+
"""
|
|
221
|
+
moment = self._require_moment(moment, "matches() moment")
|
|
222
|
+
raw = self._to_stdlib(moment)
|
|
223
|
+
try:
|
|
224
|
+
return bool(
|
|
225
|
+
_Croniter.match(
|
|
226
|
+
self._expression,
|
|
227
|
+
raw,
|
|
228
|
+
second_at_beginning=self._seconds,
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
except (ValueError, TypeError, OverflowError) as exc:
|
|
232
|
+
raise ParseError(
|
|
233
|
+
f"could not evaluate cron expression {self._expression!r}: {exc}"
|
|
234
|
+
) from exc
|
|
235
|
+
|
|
236
|
+
# -- internals --------------------------------------------------------
|
|
237
|
+
|
|
238
|
+
def _require_moment(self, value: object, what: str) -> LocalDateTime | DateTime:
|
|
239
|
+
"""Validate a query moment: ``LocalDateTime`` or ``DateTime`` only."""
|
|
240
|
+
if isinstance(value, (LocalDateTime, DateTime)):
|
|
241
|
+
return value
|
|
242
|
+
raise TypeError(
|
|
243
|
+
f"{what} must be a LocalDateTime or DateTime, got {type(value).__name__}"
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
def _to_stdlib(self, moment: LocalDateTime | DateTime) -> _StdDateTime:
|
|
247
|
+
"""Convert a query moment to the stdlib datetime croniter uses.
|
|
248
|
+
|
|
249
|
+
A naive moment is read in this schedule's timezone when one
|
|
250
|
+
is set (ambiguous or nonexistent wall times raise
|
|
251
|
+
``AmbiguousTimeError`` / ``NonexistentTimeError``); otherwise
|
|
252
|
+
it stays naive. A ``DateTime`` keeps its own zone.
|
|
253
|
+
"""
|
|
254
|
+
if isinstance(moment, DateTime):
|
|
255
|
+
return _to_stdlib(moment)
|
|
256
|
+
if self._timezone is None:
|
|
257
|
+
return moment.to_datetime()
|
|
258
|
+
return moment.at_timezone(self._timezone).to_datetime()
|
|
259
|
+
|
|
260
|
+
def _convert(
|
|
261
|
+
self, value: _StdDateTime, moment: LocalDateTime | DateTime
|
|
262
|
+
) -> LocalDateTime | DateTime:
|
|
263
|
+
"""Convert a stdlib result back to the input moment's type."""
|
|
264
|
+
if isinstance(moment, DateTime):
|
|
265
|
+
return DateTime.from_datetime(value)
|
|
266
|
+
if value.tzinfo is not None:
|
|
267
|
+
return LocalDateTime(
|
|
268
|
+
value.year,
|
|
269
|
+
value.month,
|
|
270
|
+
value.day,
|
|
271
|
+
value.hour,
|
|
272
|
+
value.minute,
|
|
273
|
+
value.second,
|
|
274
|
+
microsecond=value.microsecond,
|
|
275
|
+
)
|
|
276
|
+
return LocalDateTime.from_datetime(value)
|
|
277
|
+
|
|
278
|
+
def _iterator(self, moment: LocalDateTime | DateTime) -> _Croniter[_StdDateTime]:
|
|
279
|
+
"""Build a croniter anchored at ``moment``."""
|
|
280
|
+
try:
|
|
281
|
+
return _Croniter(
|
|
282
|
+
self._expression,
|
|
283
|
+
self._to_stdlib(moment),
|
|
284
|
+
ret_type=_StdDateTime,
|
|
285
|
+
second_at_beginning=self._seconds,
|
|
286
|
+
)
|
|
287
|
+
except (ValueError, TypeError, OverflowError) as exc:
|
|
288
|
+
raise ParseError(
|
|
289
|
+
f"could not evaluate cron expression {self._expression!r}: {exc}"
|
|
290
|
+
) from exc
|
|
291
|
+
|
|
292
|
+
def __eq__(self, other: object) -> bool:
|
|
293
|
+
if isinstance(other, Cron):
|
|
294
|
+
return (
|
|
295
|
+
self._expression == other._expression
|
|
296
|
+
and self._timezone == other._timezone
|
|
297
|
+
)
|
|
298
|
+
return NotImplemented
|
|
299
|
+
|
|
300
|
+
def __hash__(self) -> int:
|
|
301
|
+
return hash((self._expression, self._timezone))
|
|
302
|
+
|
|
303
|
+
def __repr__(self) -> str:
|
|
304
|
+
if self._timezone is None:
|
|
305
|
+
return f"Cron({self._expression!r})"
|
|
306
|
+
return f"Cron({self._expression!r}, timezone={self._timezone!r})"
|