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,125 @@
|
|
|
1
|
+
"""TimeZone: a named IANA time zone such as ``"America/New_York"``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
7
|
+
|
|
8
|
+
import whenever
|
|
9
|
+
|
|
10
|
+
from ..errors import TimeCoreError, UnknownTimeZoneError
|
|
11
|
+
from ._common import _map_whenever_errors, _require_instance, _require_str
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from .duration import Duration
|
|
15
|
+
from .instant import Instant
|
|
16
|
+
from .local_datetime import LocalDateTime
|
|
17
|
+
from .zoned_datetime import DateTime
|
|
18
|
+
|
|
19
|
+
__all__ = ["TimeZone", "available_timezones"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TimeZone:
|
|
23
|
+
"""A named IANA time zone, identified by its key.
|
|
24
|
+
|
|
25
|
+
Example:
|
|
26
|
+
>>> TimeZone("America/New_York")
|
|
27
|
+
TimeZone('America/New_York')
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
__slots__ = ("_key",)
|
|
31
|
+
|
|
32
|
+
def __init__(self, key: str) -> None:
|
|
33
|
+
key = _require_str(key, "TimeZone()")
|
|
34
|
+
# Validate against the same database whenever uses. Constructing
|
|
35
|
+
# a throwaway zoned datetime on January 1 (never ambiguous) is
|
|
36
|
+
# the authoritative check; it raises TimeZoneNotFoundError for
|
|
37
|
+
# unknown keys.
|
|
38
|
+
with _map_whenever_errors():
|
|
39
|
+
whenever.ZonedDateTime(2000, 1, 1, tz=key)
|
|
40
|
+
self._key = key
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def local(cls) -> TimeZone:
|
|
44
|
+
"""Return the system's local time zone."""
|
|
45
|
+
try:
|
|
46
|
+
import tzlocal
|
|
47
|
+
|
|
48
|
+
zone = tzlocal.get_localzone()
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
raise TimeCoreError(
|
|
51
|
+
f"could not determine the local time zone: {exc}"
|
|
52
|
+
) from exc
|
|
53
|
+
key = getattr(zone, "key", None) or getattr(zone, "zone", None) or str(zone)
|
|
54
|
+
if not isinstance(key, str) or not key:
|
|
55
|
+
raise TimeCoreError(
|
|
56
|
+
f"could not determine the local time zone: got {zone!r}"
|
|
57
|
+
)
|
|
58
|
+
return cls(key)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def utc(cls) -> TimeZone:
|
|
62
|
+
"""Return the UTC time zone."""
|
|
63
|
+
return cls("UTC")
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def key(self) -> str:
|
|
67
|
+
"""The IANA time zone key, e.g. ``"America/New_York"``."""
|
|
68
|
+
return self._key
|
|
69
|
+
|
|
70
|
+
def to_zoneinfo(self) -> ZoneInfo:
|
|
71
|
+
"""Convert to a standard-library ``zoneinfo.ZoneInfo``."""
|
|
72
|
+
try:
|
|
73
|
+
return ZoneInfo(self._key)
|
|
74
|
+
except (ZoneInfoNotFoundError, ValueError) as exc:
|
|
75
|
+
raise UnknownTimeZoneError(f"unknown time zone: {self._key!r}") from exc
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def from_zoneinfo(cls, zoneinfo: ZoneInfo) -> TimeZone:
|
|
79
|
+
"""Create a :class:`TimeZone` from a ``zoneinfo.ZoneInfo``."""
|
|
80
|
+
zoneinfo = _require_instance(zoneinfo, ZoneInfo, "TimeZone.from_zoneinfo()")
|
|
81
|
+
return cls(zoneinfo.key)
|
|
82
|
+
|
|
83
|
+
def offset_at(
|
|
84
|
+
self, instant_or_datetime: Instant | DateTime | LocalDateTime
|
|
85
|
+
) -> Duration:
|
|
86
|
+
"""Return the UTC offset of this zone at the given moment.
|
|
87
|
+
|
|
88
|
+
Accepts an :class:`~timecore.core.Instant`, a
|
|
89
|
+
:class:`~timecore.core.DateTime`, or a
|
|
90
|
+
:class:`~timecore.core.LocalDateTime` (whose wall time is read in
|
|
91
|
+
this zone; ambiguous or nonexistent wall times raise
|
|
92
|
+
:class:`~timecore.errors.AmbiguousTimeError` /
|
|
93
|
+
:class:`~timecore.errors.NonexistentTimeError`).
|
|
94
|
+
"""
|
|
95
|
+
from .instant import Instant
|
|
96
|
+
from .local_datetime import LocalDateTime
|
|
97
|
+
from .zoned_datetime import DateTime
|
|
98
|
+
|
|
99
|
+
if isinstance(instant_or_datetime, Instant):
|
|
100
|
+
zoned = instant_or_datetime.to_datetime(self)
|
|
101
|
+
elif isinstance(instant_or_datetime, DateTime):
|
|
102
|
+
zoned = instant_or_datetime.astimezone(self)
|
|
103
|
+
else:
|
|
104
|
+
local = _require_instance(instant_or_datetime, LocalDateTime, "offset_at()")
|
|
105
|
+
zoned = local.at_timezone(self)
|
|
106
|
+
return zoned.utcoffset()
|
|
107
|
+
|
|
108
|
+
def __eq__(self, other: object) -> bool:
|
|
109
|
+
if isinstance(other, TimeZone):
|
|
110
|
+
return self._key == other._key
|
|
111
|
+
return NotImplemented
|
|
112
|
+
|
|
113
|
+
def __hash__(self) -> int:
|
|
114
|
+
return hash(self._key)
|
|
115
|
+
|
|
116
|
+
def __repr__(self) -> str:
|
|
117
|
+
return f"TimeZone({self._key!r})"
|
|
118
|
+
|
|
119
|
+
def __str__(self) -> str:
|
|
120
|
+
return self._key
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def available_timezones() -> tuple[str, ...]:
|
|
124
|
+
"""Return the sorted tuple of all known IANA time zone keys."""
|
|
125
|
+
return tuple(whenever.available_timezones())
|
timecore/core/weekday.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Weekday: the day of the week, Monday (0) through Sunday (6)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
|
|
7
|
+
__all__ = ["Weekday"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Weekday(IntEnum):
|
|
11
|
+
"""The day of the week, matching :meth:`datetime.date.weekday`.
|
|
12
|
+
|
|
13
|
+
``MONDAY`` is 0 and ``SUNDAY`` is 6.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
MONDAY = 0
|
|
17
|
+
TUESDAY = 1
|
|
18
|
+
WEDNESDAY = 2
|
|
19
|
+
THURSDAY = 3
|
|
20
|
+
FRIDAY = 4
|
|
21
|
+
SATURDAY = 5
|
|
22
|
+
SUNDAY = 6
|
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""DateTime: a date and time in a named time zone (DST-aware)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime as _StdDateTime
|
|
6
|
+
|
|
7
|
+
import whenever
|
|
8
|
+
|
|
9
|
+
from ..errors import ParseError, TimeCoreError, UnknownTimeZoneError
|
|
10
|
+
from ._common import (
|
|
11
|
+
Clock,
|
|
12
|
+
Disambiguation,
|
|
13
|
+
_check_us_precision,
|
|
14
|
+
_exact_parts,
|
|
15
|
+
_format_value,
|
|
16
|
+
_instant_to_zoned,
|
|
17
|
+
_map_whenever_errors,
|
|
18
|
+
_now_instant,
|
|
19
|
+
_require_instance,
|
|
20
|
+
_require_str,
|
|
21
|
+
_resolve_timezone,
|
|
22
|
+
_resolve_timezone_required,
|
|
23
|
+
_strptime,
|
|
24
|
+
_validate_disambiguation,
|
|
25
|
+
_zoned_to_tz,
|
|
26
|
+
)
|
|
27
|
+
from .date import Date
|
|
28
|
+
from .duration import Duration
|
|
29
|
+
from .instant import Instant
|
|
30
|
+
from .local_datetime import LocalDateTime
|
|
31
|
+
from .period import Period
|
|
32
|
+
from .time import Time
|
|
33
|
+
from .timezone import TimeZone
|
|
34
|
+
from .weekday import Weekday
|
|
35
|
+
|
|
36
|
+
__all__ = ["DateTime"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DateTime:
|
|
40
|
+
"""A date and time in a named time zone, with nanosecond precision.
|
|
41
|
+
|
|
42
|
+
Arithmetic is DST-aware: adding a :class:`~timecore.core.Duration`
|
|
43
|
+
of 1 day moves the instant by exactly 24 hours (so the wall time
|
|
44
|
+
may shift across a DST transition), while adding a
|
|
45
|
+
:class:`~timecore.core.Period` of 1 day keeps the wall time and moves
|
|
46
|
+
the instant by 23 or 25 hours instead.
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
>>> DateTime(2026, 1, 15, 10, 30, timezone="America/New_York")
|
|
50
|
+
DateTime(2026, 1, 15, 10, 30, timezone=TimeZone('America/New_York'))
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
__slots__ = ("_inner",)
|
|
54
|
+
|
|
55
|
+
# The wrapped whenever value; declared here so pyright knows its type.
|
|
56
|
+
_inner: whenever.ZonedDateTime
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
year: int,
|
|
61
|
+
month: int,
|
|
62
|
+
day: int,
|
|
63
|
+
hour: int = 0,
|
|
64
|
+
minute: int = 0,
|
|
65
|
+
second: int = 0,
|
|
66
|
+
microsecond: int = 0,
|
|
67
|
+
nanosecond: int = 0,
|
|
68
|
+
*,
|
|
69
|
+
timezone: TimeZone | str,
|
|
70
|
+
disambiguation: Disambiguation = "raise",
|
|
71
|
+
) -> None:
|
|
72
|
+
# See Time: microsecond and nanosecond add up to the sub-second part.
|
|
73
|
+
total_ns = microsecond * 1_000 + nanosecond
|
|
74
|
+
if isinstance(timezone, str):
|
|
75
|
+
key = TimeZone(timezone).key
|
|
76
|
+
else:
|
|
77
|
+
key = _require_instance(timezone, TimeZone, "DateTime() timezone").key
|
|
78
|
+
disambiguation = _validate_disambiguation(disambiguation)
|
|
79
|
+
with _map_whenever_errors():
|
|
80
|
+
self._inner = whenever.ZonedDateTime(
|
|
81
|
+
year,
|
|
82
|
+
month,
|
|
83
|
+
day,
|
|
84
|
+
hour,
|
|
85
|
+
minute,
|
|
86
|
+
second,
|
|
87
|
+
nanosecond=total_ns,
|
|
88
|
+
tz=key,
|
|
89
|
+
disambiguation=disambiguation,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_whenever(cls, inner: whenever.ZonedDateTime) -> DateTime:
|
|
94
|
+
"""Wrap a whenever ``ZonedDateTime``.
|
|
95
|
+
|
|
96
|
+
Internal constructor; not part of the public API.
|
|
97
|
+
"""
|
|
98
|
+
obj = cls.__new__(cls)
|
|
99
|
+
obj._inner = inner
|
|
100
|
+
return obj
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def now(
|
|
104
|
+
cls,
|
|
105
|
+
*,
|
|
106
|
+
timezone: TimeZone | str | None = None,
|
|
107
|
+
clock: Clock | None = None,
|
|
108
|
+
) -> DateTime:
|
|
109
|
+
"""Return the current date and time in ``timezone`` (default: local zone).
|
|
110
|
+
|
|
111
|
+
Pass ``clock`` (an object with a ``now() -> Instant`` method) to
|
|
112
|
+
determine "now" deterministically, e.g. in tests.
|
|
113
|
+
"""
|
|
114
|
+
instant = _now_instant(clock)
|
|
115
|
+
tz = _resolve_timezone(timezone)
|
|
116
|
+
return instant.to_datetime(tz)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def parse(cls, text: str, *, format: str | None = None) -> DateTime:
|
|
120
|
+
"""Parse an ISO 8601 zoned datetime.
|
|
121
|
+
|
|
122
|
+
The input must carry a time zone: either a ``[Zone]`` suffix
|
|
123
|
+
(``"2026-01-15T10:30:00-05:00[America/New_York]"``), a ``Z``
|
|
124
|
+
suffix (read as UTC), or a numeric offset. A naive input (no
|
|
125
|
+
offset, no zone) raises :class:`~timecore.errors.ParseError`.
|
|
126
|
+
|
|
127
|
+
With ``format``, parse with a ``strftime`` pattern instead
|
|
128
|
+
(English month names only, locale-independent); the parsed value
|
|
129
|
+
must be time-zone aware.
|
|
130
|
+
|
|
131
|
+
Note on bare offsets: whenever's ``ZonedDateTime`` cannot
|
|
132
|
+
represent a fixed offset without a zone name, so an offset-only
|
|
133
|
+
input with a whole-hour offset is read into the matching
|
|
134
|
+
``Etc/GMT`` zone (e.g. ``-05:00`` becomes ``Etc/GMT+5``), which
|
|
135
|
+
preserves the instant, wall time, and offset exactly. A
|
|
136
|
+
non-whole-hour bare offset (e.g. ``+05:30``) has no such zone
|
|
137
|
+
and raises ``ParseError``; give a named zone instead.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
ParseError: If ``text`` is not a valid zoned datetime.
|
|
141
|
+
UnknownTimeZoneError: If the named zone is unknown.
|
|
142
|
+
"""
|
|
143
|
+
text = _require_str(text, "DateTime.parse()")
|
|
144
|
+
if format is not None:
|
|
145
|
+
format = _require_str(format, "DateTime.parse() format")
|
|
146
|
+
parsed = _strptime(text, format)
|
|
147
|
+
if parsed.tzinfo is None:
|
|
148
|
+
raise ParseError(
|
|
149
|
+
f"could not parse {text!r} as a DateTime: "
|
|
150
|
+
"input carries no time zone offset"
|
|
151
|
+
)
|
|
152
|
+
return cls.from_datetime(parsed)
|
|
153
|
+
try:
|
|
154
|
+
return cls.from_whenever(whenever.ZonedDateTime.parse_iso(text))
|
|
155
|
+
except whenever.TimeZoneNotFoundError as exc:
|
|
156
|
+
raise UnknownTimeZoneError(str(exc)) from exc
|
|
157
|
+
except ValueError:
|
|
158
|
+
pass
|
|
159
|
+
# No zone suffix: try an offset-only (or "Z") reading via
|
|
160
|
+
# OffsetDateTime, which accepts bare offsets.
|
|
161
|
+
try:
|
|
162
|
+
offset_dt = whenever.OffsetDateTime.parse_iso(text)
|
|
163
|
+
except ValueError as exc:
|
|
164
|
+
raise ParseError(
|
|
165
|
+
f"could not parse {text!r} as an ISO 8601 zoned datetime; "
|
|
166
|
+
"input must carry an offset or a time zone"
|
|
167
|
+
) from exc
|
|
168
|
+
offset_ns = int(offset_dt.offset.total("nanoseconds"))
|
|
169
|
+
if offset_ns % 3_600_000_000_000:
|
|
170
|
+
raise ParseError(
|
|
171
|
+
f"could not parse {text!r} as a DateTime: a bare offset "
|
|
172
|
+
"with minutes has no named time zone; give a zone such as "
|
|
173
|
+
"'2026-01-15T10:30:00+05:30[Asia/Kolkata]'"
|
|
174
|
+
)
|
|
175
|
+
offset_hours = offset_ns // 3_600_000_000_000
|
|
176
|
+
if offset_hours == 0:
|
|
177
|
+
key = "UTC"
|
|
178
|
+
elif offset_hours < 0:
|
|
179
|
+
# Etc/GMT signs are inverted: -05:00 is Etc/GMT+5.
|
|
180
|
+
key = f"Etc/GMT+{-offset_hours}"
|
|
181
|
+
else:
|
|
182
|
+
key = f"Etc/GMT-{offset_hours}"
|
|
183
|
+
with _map_whenever_errors():
|
|
184
|
+
return cls.from_whenever(_instant_to_zoned(offset_dt.to_instant(), key))
|
|
185
|
+
|
|
186
|
+
@classmethod
|
|
187
|
+
def from_datetime(cls, value: _StdDateTime) -> DateTime:
|
|
188
|
+
"""Create a :class:`DateTime` from an aware stdlib ``datetime``.
|
|
189
|
+
|
|
190
|
+
The datetime's ``tzinfo`` must be a ``zoneinfo.ZoneInfo``, UTC,
|
|
191
|
+
or a fixed offset with a whole number of hours (mapped to the
|
|
192
|
+
matching ``Etc/GMT`` zone, as in :meth:`parse`).
|
|
193
|
+
|
|
194
|
+
Raises:
|
|
195
|
+
ValueError: If ``value`` is naive, or its fixed offset has
|
|
196
|
+
a non-whole-hour component.
|
|
197
|
+
"""
|
|
198
|
+
value = _require_instance(value, _StdDateTime, "DateTime.from_datetime()")
|
|
199
|
+
if value.tzinfo is None:
|
|
200
|
+
raise ValueError(
|
|
201
|
+
"DateTime.from_datetime() expects an aware datetime; "
|
|
202
|
+
"use LocalDateTime.from_datetime() for naive datetimes"
|
|
203
|
+
)
|
|
204
|
+
tzinfo = value.tzinfo
|
|
205
|
+
raw_key = getattr(tzinfo, "key", None)
|
|
206
|
+
if isinstance(raw_key, str):
|
|
207
|
+
key = raw_key
|
|
208
|
+
else:
|
|
209
|
+
offset = value.utcoffset()
|
|
210
|
+
if offset is None:
|
|
211
|
+
raise ValueError(
|
|
212
|
+
"DateTime.from_datetime() cannot determine the UTC offset "
|
|
213
|
+
f"of {value!r}"
|
|
214
|
+
)
|
|
215
|
+
total_seconds = offset.total_seconds()
|
|
216
|
+
if total_seconds % 3_600:
|
|
217
|
+
raise ValueError(
|
|
218
|
+
"DateTime.from_datetime() cannot represent a fixed offset "
|
|
219
|
+
"with minutes; use a zoneinfo.ZoneInfo tzinfo instead"
|
|
220
|
+
)
|
|
221
|
+
offset_hours = int(total_seconds // 3_600)
|
|
222
|
+
if offset_hours == 0:
|
|
223
|
+
key = "UTC"
|
|
224
|
+
elif offset_hours < 0:
|
|
225
|
+
key = f"Etc/GMT+{-offset_hours}"
|
|
226
|
+
else:
|
|
227
|
+
key = f"Etc/GMT-{offset_hours}"
|
|
228
|
+
with _map_whenever_errors():
|
|
229
|
+
instant = Instant.from_whenever(whenever.Instant(value))
|
|
230
|
+
return cls.from_instant(instant, TimeZone(key))
|
|
231
|
+
|
|
232
|
+
@classmethod
|
|
233
|
+
def from_instant(cls, instant: Instant, timezone: TimeZone | str) -> DateTime:
|
|
234
|
+
"""Create a :class:`DateTime` showing ``instant`` in ``timezone``."""
|
|
235
|
+
instant = _require_instance(instant, Instant, "DateTime.from_instant()")
|
|
236
|
+
tz = _resolve_timezone_required(timezone)
|
|
237
|
+
return instant.to_datetime(tz)
|
|
238
|
+
|
|
239
|
+
def to_instant(self) -> Instant:
|
|
240
|
+
"""Return the absolute moment this zoned datetime represents."""
|
|
241
|
+
return Instant.from_whenever(self._inner.to_instant())
|
|
242
|
+
|
|
243
|
+
def to_local_datetime(self) -> LocalDateTime:
|
|
244
|
+
"""Return the wall-clock reading as a ``LocalDateTime``."""
|
|
245
|
+
return LocalDateTime.from_whenever(self._inner.to_plain())
|
|
246
|
+
|
|
247
|
+
def to_datetime(self) -> _StdDateTime:
|
|
248
|
+
"""Convert to an aware standard-library ``datetime``.
|
|
249
|
+
|
|
250
|
+
Raises:
|
|
251
|
+
ValueError: If this value has a sub-microsecond remainder,
|
|
252
|
+
which a stdlib ``datetime`` cannot represent.
|
|
253
|
+
"""
|
|
254
|
+
_check_us_precision(self.nanosecond, "DateTime")
|
|
255
|
+
return self._inner.to_stdlib()
|
|
256
|
+
|
|
257
|
+
def date(self) -> Date:
|
|
258
|
+
"""Return the date part in this zone."""
|
|
259
|
+
return self.to_local_datetime().date()
|
|
260
|
+
|
|
261
|
+
def time(self) -> Time:
|
|
262
|
+
"""Return the time-of-day part in this zone."""
|
|
263
|
+
return self.to_local_datetime().time()
|
|
264
|
+
|
|
265
|
+
def astimezone(self, timezone: TimeZone | str) -> DateTime:
|
|
266
|
+
"""Return this moment shown in ``timezone``."""
|
|
267
|
+
tz = _resolve_timezone_required(timezone)
|
|
268
|
+
with _map_whenever_errors():
|
|
269
|
+
return DateTime.from_whenever(_zoned_to_tz(self._inner, tz.key))
|
|
270
|
+
|
|
271
|
+
@property
|
|
272
|
+
def timezone(self) -> TimeZone:
|
|
273
|
+
"""The time zone this datetime is in."""
|
|
274
|
+
tz_id = self._inner.tz_id
|
|
275
|
+
if tz_id is None:
|
|
276
|
+
# whenever types tz_id as str | None, but a ZonedDateTime
|
|
277
|
+
# built through TimeCore always carries a zone identifier.
|
|
278
|
+
raise TimeCoreError("this DateTime has no time zone identifier")
|
|
279
|
+
return TimeZone(tz_id)
|
|
280
|
+
|
|
281
|
+
def utcoffset(self) -> Duration:
|
|
282
|
+
"""Return the UTC offset in effect at this datetime."""
|
|
283
|
+
return Duration.from_whenever(self._inner.offset)
|
|
284
|
+
|
|
285
|
+
@property
|
|
286
|
+
def year(self) -> int:
|
|
287
|
+
"""The year, e.g. 2026."""
|
|
288
|
+
return self._inner.year
|
|
289
|
+
|
|
290
|
+
@property
|
|
291
|
+
def month(self) -> int:
|
|
292
|
+
"""The month, 1-12."""
|
|
293
|
+
return self._inner.month
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def day(self) -> int:
|
|
297
|
+
"""The day of the month, 1-31."""
|
|
298
|
+
return self._inner.day
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def hour(self) -> int:
|
|
302
|
+
"""The hour, 0-23."""
|
|
303
|
+
return self._inner.hour
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def minute(self) -> int:
|
|
307
|
+
"""The minute, 0-59."""
|
|
308
|
+
return self._inner.minute
|
|
309
|
+
|
|
310
|
+
@property
|
|
311
|
+
def second(self) -> int:
|
|
312
|
+
"""The second, 0-59."""
|
|
313
|
+
return self._inner.second
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def microsecond(self) -> int:
|
|
317
|
+
"""The microsecond component, 0-999999."""
|
|
318
|
+
return self.nanosecond // 1_000
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def nanosecond(self) -> int:
|
|
322
|
+
"""The sub-second part in nanoseconds, 0-999999999."""
|
|
323
|
+
return self._inner.nanosecond
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def weekday(self) -> Weekday:
|
|
327
|
+
"""The day of the week."""
|
|
328
|
+
return Weekday[self._inner.day_of_week().name]
|
|
329
|
+
|
|
330
|
+
def isoformat(self) -> str:
|
|
331
|
+
"""Return the ISO 8601 form, e.g. ``"2026-01-15T10:30:00-05:00[America/New_York]"``."""
|
|
332
|
+
return self._inner.format_iso()
|
|
333
|
+
|
|
334
|
+
def format(
|
|
335
|
+
self,
|
|
336
|
+
style: str = "medium",
|
|
337
|
+
locale: str | None = None,
|
|
338
|
+
pattern: str | None = None,
|
|
339
|
+
) -> str:
|
|
340
|
+
"""Format this value (see :func:`timecore.core._common._format_value`).
|
|
341
|
+
|
|
342
|
+
``style`` is one of ``"short"``, ``"medium"``, ``"long"``,
|
|
343
|
+
``"full"``; ``pattern`` is a Babel pattern. The default call
|
|
344
|
+
returns Babel's ``"medium"`` style output.
|
|
345
|
+
"""
|
|
346
|
+
return _format_value(self, style=style, locale=locale, pattern=pattern)
|
|
347
|
+
|
|
348
|
+
def __add__(self, other: object) -> DateTime:
|
|
349
|
+
if isinstance(other, Duration):
|
|
350
|
+
# Exact time: the instant moves by exactly this long, so the
|
|
351
|
+
# wall time may shift across a DST transition.
|
|
352
|
+
hours, minutes, seconds, ms, us, ns = _exact_parts(
|
|
353
|
+
other.total_nanoseconds()
|
|
354
|
+
)
|
|
355
|
+
with _map_whenever_errors():
|
|
356
|
+
return DateTime.from_whenever(
|
|
357
|
+
self._inner.add(
|
|
358
|
+
hours=hours,
|
|
359
|
+
minutes=minutes,
|
|
360
|
+
seconds=seconds,
|
|
361
|
+
milliseconds=ms,
|
|
362
|
+
microseconds=us,
|
|
363
|
+
nanoseconds=ns,
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
if isinstance(other, Period):
|
|
367
|
+
# Calendar time: the wall time is kept, so the instant moves
|
|
368
|
+
# by 23 or 25 hours across a DST transition. whenever's
|
|
369
|
+
# default ("compatible") disambiguation applies if the result
|
|
370
|
+
# lands on a repeated or skipped local time.
|
|
371
|
+
with _map_whenever_errors():
|
|
372
|
+
return DateTime.from_whenever(
|
|
373
|
+
self._inner.add(
|
|
374
|
+
years=other.years,
|
|
375
|
+
months=other.months,
|
|
376
|
+
weeks=other.weeks,
|
|
377
|
+
days=other.days,
|
|
378
|
+
hours=other.hours,
|
|
379
|
+
minutes=other.minutes,
|
|
380
|
+
seconds=other.seconds,
|
|
381
|
+
milliseconds=other.milliseconds,
|
|
382
|
+
microseconds=other.microseconds,
|
|
383
|
+
nanoseconds=other.nanoseconds,
|
|
384
|
+
)
|
|
385
|
+
)
|
|
386
|
+
return NotImplemented
|
|
387
|
+
|
|
388
|
+
def __radd__(self, other: object) -> DateTime:
|
|
389
|
+
return self.__add__(other)
|
|
390
|
+
|
|
391
|
+
def __sub__(self, other: object) -> DateTime | Duration:
|
|
392
|
+
if isinstance(other, (Duration, Period)):
|
|
393
|
+
return self.__add__(-other)
|
|
394
|
+
if isinstance(other, DateTime):
|
|
395
|
+
return self.to_instant() - other.to_instant()
|
|
396
|
+
return NotImplemented
|
|
397
|
+
|
|
398
|
+
def __eq__(self, other: object) -> bool:
|
|
399
|
+
if isinstance(other, DateTime):
|
|
400
|
+
return self._inner == other._inner
|
|
401
|
+
return NotImplemented
|
|
402
|
+
|
|
403
|
+
def __lt__(self, other: object) -> bool:
|
|
404
|
+
if isinstance(other, DateTime):
|
|
405
|
+
return self._inner < other._inner
|
|
406
|
+
return NotImplemented
|
|
407
|
+
|
|
408
|
+
def __le__(self, other: object) -> bool:
|
|
409
|
+
if isinstance(other, DateTime):
|
|
410
|
+
return self._inner <= other._inner
|
|
411
|
+
return NotImplemented
|
|
412
|
+
|
|
413
|
+
def __gt__(self, other: object) -> bool:
|
|
414
|
+
if isinstance(other, DateTime):
|
|
415
|
+
return self._inner > other._inner
|
|
416
|
+
return NotImplemented
|
|
417
|
+
|
|
418
|
+
def __ge__(self, other: object) -> bool:
|
|
419
|
+
if isinstance(other, DateTime):
|
|
420
|
+
return self._inner >= other._inner
|
|
421
|
+
return NotImplemented
|
|
422
|
+
|
|
423
|
+
def __hash__(self) -> int:
|
|
424
|
+
return hash(self._inner)
|
|
425
|
+
|
|
426
|
+
def __repr__(self) -> str:
|
|
427
|
+
base = (
|
|
428
|
+
f"DateTime({self.year}, {self.month}, {self.day}, "
|
|
429
|
+
f"{self.hour}, {self.minute}, {self.second}"
|
|
430
|
+
)
|
|
431
|
+
if self.nanosecond:
|
|
432
|
+
if self.nanosecond % 1_000 == 0:
|
|
433
|
+
base += f", microsecond={self.microsecond}"
|
|
434
|
+
else:
|
|
435
|
+
base += (
|
|
436
|
+
f", microsecond={self.microsecond}, "
|
|
437
|
+
f"nanosecond={self.nanosecond % 1_000}"
|
|
438
|
+
)
|
|
439
|
+
return base + f", timezone=TimeZone({self.timezone.key!r}))"
|
|
440
|
+
|
|
441
|
+
def __str__(self) -> str:
|
|
442
|
+
return self.isoformat()
|
timecore/errors.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Error types for TimeCore.
|
|
2
|
+
|
|
3
|
+
Every public function that can fail on bad input raises one of these
|
|
4
|
+
errors (or plain ``ValueError`` / ``TypeError`` for programmer errors such
|
|
5
|
+
as wrong argument types). All concrete errors subclass ``ValueError`` so
|
|
6
|
+
they are catchable as ``ValueError``. Third-party exceptions are wrapped
|
|
7
|
+
at the boundary into one of these errors and never leak into the public API.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"AmbiguousTimeError",
|
|
14
|
+
"InvalidIntervalError",
|
|
15
|
+
"InvalidLocaleError",
|
|
16
|
+
"NonexistentTimeError",
|
|
17
|
+
"ParseError",
|
|
18
|
+
"TimeCoreError",
|
|
19
|
+
"UnknownTimeZoneError",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TimeCoreError(Exception):
|
|
24
|
+
"""Base class for all TimeCore errors."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ParseError(TimeCoreError, ValueError):
|
|
28
|
+
"""Raised when a string cannot be parsed into a temporal value."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AmbiguousTimeError(TimeCoreError, ValueError):
|
|
32
|
+
"""Raised for a repeated local time (DST fall-back)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class NonexistentTimeError(TimeCoreError, ValueError):
|
|
36
|
+
"""Raised for a skipped local time (DST spring-forward)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class UnknownTimeZoneError(TimeCoreError, ValueError):
|
|
40
|
+
"""Raised when a time zone key is not known."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class InvalidIntervalError(TimeCoreError, ValueError):
|
|
44
|
+
"""Raised when an interval is invalid (e.g. mismatched endpoints)."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class InvalidLocaleError(TimeCoreError, ValueError):
|
|
48
|
+
"""Raised when a locale is not known or not supported."""
|