python-intl 0.1.0__tar.gz → 0.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-intl
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Add your description here
5
5
  Author: David Danier
6
6
  Author-email: David Danier <david.danier@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -0,0 +1,322 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import datetime as dt
5
+ from functools import cache, cached_property
6
+ from typing import TYPE_CHECKING, Literal
7
+
8
+ import icu # type: ignore[import-untyped]
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterable
12
+ from typing import NotRequired, TypedDict
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ type LocaleMatcherT = Literal["best fit", "lookup"]
17
+ type Hour12T = bool | None
18
+ type HourCycleT = Literal["h11", "h12", "h23", "h24"] | None
19
+
20
+ type EraFormatT = Literal["long", "short", "narrow"]
21
+ type YearFormatT = Literal["numeric", "2-digit"]
22
+ type MonthFormatT = Literal["numeric", "2-digit", "long", "short", "narrow"]
23
+ type WeekdayFormatT = Literal["long", "short", "narrow"]
24
+ type DayFormatT = Literal["numeric", "2-digit"]
25
+ type DayPeriodFormatT = Literal["long", "short", "narrow"]
26
+ type HourFormatT = Literal["numeric", "2-digit"]
27
+ type MinuteFormatT = Literal["numeric", "2-digit"]
28
+ type SecondFormatT = Literal["numeric", "2-digit"]
29
+ type FractionSecondDigitsFormatT = Literal[1, 2, 3]
30
+ type TimezoneNameFormatT = Literal[
31
+ "short",
32
+ "long",
33
+ "short_offset",
34
+ "long_offset",
35
+ "short_generic",
36
+ "long_generic",
37
+ ]
38
+ type AnyFormatT = (
39
+ EraFormatT
40
+ | YearFormatT
41
+ | MonthFormatT
42
+ | WeekdayFormatT
43
+ | DayFormatT
44
+ | DayPeriodFormatT
45
+ | HourFormatT
46
+ | MinuteFormatT
47
+ | SecondFormatT
48
+ | FractionSecondDigitsFormatT
49
+ | TimezoneNameFormatT
50
+ )
51
+
52
+ # Important: Must be the same as DateTimeFormatOptions
53
+ # (nothing is required, as this will be used to construct a
54
+ # DateTimeFormatOptions instance, so default values apply then)
55
+ class DateTimeFormatOptionsDictT(TypedDict):
56
+ locale_matcher: NotRequired[LocaleMatcherT]
57
+ hour12: NotRequired[Hour12T]
58
+ hour_cycle: NotRequired[HourCycleT]
59
+
60
+ era: NotRequired[EraFormatT]
61
+ year: NotRequired[YearFormatT]
62
+ month: NotRequired[MonthFormatT]
63
+ weekday: NotRequired[WeekdayFormatT]
64
+ day: NotRequired[DayFormatT]
65
+ day_period: NotRequired[DayPeriodFormatT]
66
+ hour: NotRequired[HourFormatT]
67
+ minute: NotRequired[MinuteFormatT]
68
+ second: NotRequired[SecondFormatT]
69
+ fraction_second_digits: NotRequired[FractionSecondDigitsFormatT]
70
+ time_zone_name: NotRequired[TimezoneNameFormatT]
71
+
72
+
73
+ _TIMEZONE_NAME_JS_MAPPING: dict[str | None, str] = {
74
+ "short_offset": "shortOffset",
75
+ "long_offset": "longOffset",
76
+ "short_generic": "shortGeneric",
77
+ "long_generic": "longGeneric",
78
+ }
79
+
80
+
81
+ @dataclasses.dataclass(frozen=True, kw_only=True)
82
+ class DateTimeFormatOptions:
83
+ locale_matcher: LocaleMatcherT = "best fit"
84
+ hour12: Hour12T = None
85
+ hour_cycle: HourCycleT = None
86
+
87
+ era: EraFormatT | None = None
88
+ year: YearFormatT | None = None
89
+ month: MonthFormatT | None = None
90
+ weekday: WeekdayFormatT | None = None
91
+ day: DayFormatT | None = None
92
+ day_period: DayPeriodFormatT | None = None
93
+ hour: HourFormatT | None = None
94
+ minute: MinuteFormatT | None = None
95
+ second: SecondFormatT | None = None
96
+ fraction_second_digits: FractionSecondDigitsFormatT | None = None
97
+ time_zone_name: TimezoneNameFormatT | None = None
98
+
99
+ def to_json(self) -> dict[str, str | int]:
100
+ return {
101
+ k: v
102
+ for k, v in (
103
+ ("era", self.era),
104
+ ("year", self.year),
105
+ ("month", self.month),
106
+ ("weekday", self.weekday),
107
+ ("day", self.day),
108
+ ("dayPeriod", self.day_period),
109
+ ("hour", self.hour),
110
+ ("minute", self.minute),
111
+ ("second", self.second),
112
+ ("fractionalSecondDigits", self.fraction_second_digits),
113
+ ("timeZoneName", _TIMEZONE_NAME_JS_MAPPING.get(self.time_zone_name, self.time_zone_name)),
114
+ )
115
+ if v is not None
116
+ }
117
+
118
+
119
+ def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[str]:
120
+ skeleton_parts: list[str | tuple[str, ...]] = []
121
+
122
+ # Note: The parts should be ordered from big to small.
123
+
124
+ match options.era:
125
+ case "short":
126
+ skeleton_parts.append("G")
127
+ case "long":
128
+ skeleton_parts.append("GGGG")
129
+ case "narrow":
130
+ skeleton_parts.append("GGGGG")
131
+
132
+ match options.year:
133
+ case "numeric":
134
+ skeleton_parts.append(("yyyy", "y"))
135
+ case "2-digit":
136
+ skeleton_parts.append("yy")
137
+
138
+ match options.month:
139
+ case "numeric":
140
+ skeleton_parts.append("M")
141
+ case "2-digit":
142
+ skeleton_parts.append("MM")
143
+ case "short":
144
+ skeleton_parts.append("MMM")
145
+ case "long":
146
+ skeleton_parts.append("MMMM")
147
+ case "narrow":
148
+ skeleton_parts.append("MMMMM")
149
+
150
+ match options.weekday:
151
+ case "short":
152
+ skeleton_parts.append("E")
153
+ case "long":
154
+ skeleton_parts.append("EEEE")
155
+ case "narrow":
156
+ skeleton_parts.append("EEEEE")
157
+
158
+ match options.day:
159
+ case "numeric":
160
+ skeleton_parts.append("d")
161
+ case "2-digit":
162
+ skeleton_parts.append("dd")
163
+
164
+ match options.day_period:
165
+ case "short":
166
+ skeleton_parts.append("B")
167
+ case "long":
168
+ skeleton_parts.append("BBBB")
169
+ case "narrow":
170
+ skeleton_parts.append("BBBBB")
171
+
172
+ match (options.hour_cycle, options.hour12, options.hour):
173
+ case ("h11", _, "numeric"):
174
+ skeleton_parts.append(("aK", "K"))
175
+ case ("h11", _, "2-digit"):
176
+ skeleton_parts.append(("aKK", "KK"))
177
+ case ("h12", _, "numeric"):
178
+ skeleton_parts.append(("ah", "h"))
179
+ case ("h12", _, "2-digit"):
180
+ skeleton_parts.append(("ahh", "hh"))
181
+ case ("h23", _, "numeric"):
182
+ skeleton_parts.append("H")
183
+ case ("h23", _, "2-digit"):
184
+ skeleton_parts.append("HH")
185
+ case ("h24", _, "numeric"):
186
+ skeleton_parts.append("k")
187
+ case ("h24", _, "2-digit"):
188
+ skeleton_parts.append("kk")
189
+ case (_, True, "numeric"):
190
+ skeleton_parts.append(("ah", "h"))
191
+ case (_, True, "2-digit"):
192
+ skeleton_parts.append(("ahh", "hh"))
193
+ case (_, False, "numeric"):
194
+ skeleton_parts.append("H")
195
+ case (_, False, "2-digit"):
196
+ skeleton_parts.append("HH")
197
+ case (_, _, "numeric"):
198
+ skeleton_parts.append("j")
199
+ case (_, _, "2-digit"):
200
+ skeleton_parts.append(("jj", "j"))
201
+
202
+ match options.minute:
203
+ case "numeric":
204
+ skeleton_parts.append("m")
205
+ case "2-digit":
206
+ skeleton_parts.append("mm")
207
+
208
+ match options.second:
209
+ case "numeric":
210
+ skeleton_parts.append("s")
211
+ case "2-digit":
212
+ skeleton_parts.append("ss")
213
+
214
+ if options.fraction_second_digits:
215
+ skeleton_parts.append("S" * options.fraction_second_digits)
216
+
217
+ match options.time_zone_name:
218
+ case "short":
219
+ skeleton_parts.append("z")
220
+ case "long":
221
+ skeleton_parts.append("zzzz")
222
+ case "short_offset":
223
+ skeleton_parts.append("Z")
224
+ case "long_offset":
225
+ skeleton_parts.append("ZZZZ")
226
+ case "short_generic":
227
+ skeleton_parts.append("v")
228
+ case "long_generic":
229
+ skeleton_parts.append("vvvv")
230
+
231
+ def generate_skeletons(prefix: str, remaining: list[str | tuple[str, ...]]) -> Iterable[str]:
232
+ if not remaining:
233
+ yield prefix
234
+ return
235
+
236
+ next_bit = remaining[0]
237
+ if isinstance(next_bit, tuple):
238
+ for next_bit_variant in next_bit:
239
+ yield from generate_skeletons(prefix + next_bit_variant, remaining[1:])
240
+ else:
241
+ yield from generate_skeletons(prefix + next_bit, remaining[1:])
242
+
243
+ yield from generate_skeletons("", skeleton_parts)
244
+
245
+
246
+ @dataclasses.dataclass(frozen=True, kw_only=True)
247
+ class MatchedFormatPattern:
248
+ skeleton: str
249
+ pattern: str
250
+
251
+ def __str__(self) -> str:
252
+ return self.pattern
253
+
254
+
255
+ class FormatPatternNotFoundException(Exception):
256
+ pass
257
+
258
+
259
+ @cache
260
+ def _options_to_format_pattern(
261
+ locale: icu.Locale, # ty: ignore[unresolved-attribute]
262
+ options: DateTimeFormatOptions,
263
+ ) -> MatchedFormatPattern:
264
+ possible_skeletons = list(_options_to_possible_skeletons(options))
265
+
266
+ generator = icu.DateTimePatternGenerator.createInstance(locale) # ty: ignore[unresolved-attribute]
267
+
268
+ # Try a perfect match
269
+ for skeleton in possible_skeletons:
270
+ pattern = generator.getPatternForSkeleton(skeleton)
271
+ if pattern:
272
+ return MatchedFormatPattern(
273
+ skeleton=skeleton,
274
+ pattern=pattern,
275
+ )
276
+
277
+ # Try to find best match
278
+ if options.locale_matcher == "best fit":
279
+ for skeleton in possible_skeletons:
280
+ pattern = generator.getBestPattern(skeleton)
281
+ if pattern:
282
+ return MatchedFormatPattern(
283
+ skeleton=skeleton,
284
+ pattern=pattern,
285
+ )
286
+
287
+ raise FormatPatternNotFoundException("Didn't find pattern for desired options")
288
+
289
+
290
+ class DateTimeFormat:
291
+ locale: str
292
+ options: DateTimeFormatOptions
293
+
294
+ def __init__(
295
+ self,
296
+ locale: str,
297
+ options: DateTimeFormatOptions | DateTimeFormatOptionsDictT,
298
+ ) -> None:
299
+ self.locale = locale
300
+ if isinstance(options, DateTimeFormatOptions):
301
+ self.options = options
302
+ else:
303
+ self.options = DateTimeFormatOptions(**options)
304
+
305
+ @cached_property
306
+ def icu_locale(self) -> icu.Locale: # ty: ignore[unresolved-attribute]
307
+ return icu.Locale(self.locale) # ty: ignore[unresolved-attribute]
308
+
309
+ @cached_property
310
+ def matched_pattern(self) -> MatchedFormatPattern:
311
+ return _options_to_format_pattern(self.icu_locale, self.options)
312
+
313
+ @cached_property
314
+ def icu_pattern(self) -> str:
315
+ return self.matched_pattern.pattern
316
+
317
+ @cached_property
318
+ def icu_date_format(self) -> icu.SimpleDateFormat: # ty: ignore[unresolved-attribute]
319
+ return icu.SimpleDateFormat(self.icu_pattern, self.icu_locale) # ty: ignore[unresolved-attribute]
320
+
321
+ def format(self, datetime_: dt.datetime, /) -> str:
322
+ return self.icu_date_format.format(datetime_)
@@ -1,358 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import dataclasses
4
- import datetime as dt
5
- from functools import cache, cached_property
6
- from typing import TYPE_CHECKING, Literal, overload
7
-
8
- import icu # type: ignore[import-untyped]
9
-
10
- if TYPE_CHECKING:
11
- from collections.abc import Iterable
12
- from typing import NotRequired, TypedDict
13
-
14
-
15
- if TYPE_CHECKING:
16
- type EraFormatT = Literal["long", "short", "narrow"]
17
- type YearFormatT = Literal["numeric", "2-digit"]
18
- type MonthFormatT = Literal["numeric", "2-digit", "long", "short", "narrow"]
19
- type WeekdayFormatT = Literal["long", "short", "narrow"]
20
- type DayFormatT = Literal["numeric", "2-digit"]
21
- type DayPeriodFormatT = Literal["long", "short", "narrow"]
22
- type HourFormatT = Literal["numeric", "2-digit"]
23
- type MinuteFormatT = Literal["numeric", "2-digit"]
24
- type SecondFormatT = Literal["numeric", "2-digit"]
25
- type FractionSecondDigitsFormatT = Literal[1, 2, 3]
26
- type TimezoneNameFormatT = Literal[
27
- "short",
28
- "long",
29
- "short_offset",
30
- "long_offset",
31
- "short_generic",
32
- "long_generic",
33
- ]
34
- type AnyFormatT = (
35
- EraFormatT
36
- | YearFormatT
37
- | MonthFormatT
38
- | WeekdayFormatT
39
- | DayFormatT
40
- | DayPeriodFormatT
41
- | HourFormatT
42
- | MinuteFormatT
43
- | SecondFormatT
44
- | FractionSecondDigitsFormatT
45
- | TimezoneNameFormatT
46
- )
47
-
48
- type EraPatternT = Literal["G", "GGGG", "GGGGG"]
49
- type YearPatternT = Literal["y", "yy", "yyyy"]
50
- type MonthPatternT = Literal["M", "MM", "MMM", "MMMM", "MMMMM"]
51
- type WeekdayPatternT = Literal["E", "EEEE", "EEEEE"]
52
- type DayPatternT = Literal["d", "dd"]
53
- type DayPeriodPatternT = Literal["a", "aaaa", "aaaaa", "b", "bbbb", "bbbbb", "B", "BBBB", "BBBBB"]
54
- type HourPatternT = Literal["j", "jj", "H", "h", "HH", "hh"]
55
- type MinutePatternT = Literal["m", "mm"]
56
- type SecondPatternT = Literal["s", "ss"]
57
- type FractionSecondDigitsPatternT = Literal["S", "SS", "SSS"]
58
- type TimezoneNamePatternT = Literal["z", "zzzz", "Z", "ZZZZ", "v", "vvvv"]
59
- type AnyPatternT = (
60
- EraPatternT
61
- | YearPatternT
62
- | MonthPatternT
63
- | WeekdayPatternT
64
- | DayPatternT
65
- | DayPeriodPatternT
66
- | HourPatternT
67
- | MinutePatternT
68
- | SecondPatternT
69
- | FractionSecondDigitsPatternT
70
- | TimezoneNamePatternT
71
- )
72
-
73
- type DatetimeFieldT = Literal[
74
- "era",
75
- "year",
76
- "month",
77
- "weekday",
78
- "day",
79
- "day_period",
80
- "hour",
81
- "minute",
82
- "second",
83
- "fraction_second_digits",
84
- "time_zone_name",
85
- ]
86
-
87
- class DateTimeFormatOptionsDictT(TypedDict):
88
- era: NotRequired[EraFormatT]
89
- year: NotRequired[YearFormatT]
90
- month: NotRequired[MonthFormatT]
91
- weekday: NotRequired[WeekdayFormatT]
92
- day: NotRequired[DayFormatT]
93
- day_period: NotRequired[DayPeriodFormatT]
94
- hour: NotRequired[HourFormatT]
95
- minute: NotRequired[MinuteFormatT]
96
- second: NotRequired[SecondFormatT]
97
- fraction_second_digits: NotRequired[FractionSecondDigitsFormatT]
98
- time_zone_name: NotRequired[TimezoneNameFormatT]
99
-
100
- class OptionsToSkeletonT(TypedDict):
101
- era: dict[EraFormatT, EraPatternT | tuple[EraPatternT, ...]]
102
- year: dict[YearFormatT, YearPatternT | tuple[YearPatternT, ...]]
103
- month: dict[MonthFormatT, MonthPatternT | tuple[MonthPatternT, ...]]
104
- weekday: dict[WeekdayFormatT, WeekdayPatternT | tuple[WeekdayPatternT, ...]]
105
- day: dict[DayFormatT, DayPatternT | tuple[DayPatternT, ...]]
106
- day_period: dict[DayPeriodFormatT, DayPeriodPatternT | tuple[DayPeriodPatternT, ...]]
107
- hour: dict[HourFormatT, HourPatternT | tuple[HourPatternT, ...]]
108
- minute: dict[MinuteFormatT, MinutePatternT | tuple[MinutePatternT, ...]]
109
- second: dict[SecondFormatT, SecondPatternT | tuple[SecondPatternT, ...]]
110
- fraction_second_digits: dict[
111
- FractionSecondDigitsFormatT,
112
- FractionSecondDigitsPatternT | tuple[FractionSecondDigitsPatternT, ...],
113
- ]
114
- time_zone_name: dict[TimezoneNameFormatT, TimezoneNamePatternT | tuple[TimezoneNamePatternT, ...]]
115
-
116
-
117
- @dataclasses.dataclass(frozen=True, kw_only=True)
118
- class DateTimeFormatOptions:
119
- era: EraFormatT | None = None
120
- year: YearFormatT | None = None
121
- month: MonthFormatT | None = None
122
- weekday: WeekdayFormatT | None = None
123
- day: DayFormatT | None = None
124
- day_period: DayPeriodFormatT | None = None
125
- hour: HourFormatT | None = None
126
- minute: MinuteFormatT | None = None
127
- second: SecondFormatT | None = None
128
- fraction_second_digits: FractionSecondDigitsFormatT | None = None
129
- time_zone_name: TimezoneNameFormatT | None = None
130
-
131
- def to_json(self) -> dict[str, str | int]:
132
- return {
133
- k: v
134
- for k, v in (
135
- ("era", self.era),
136
- ("year", self.year),
137
- ("month", self.month),
138
- ("weekday", self.weekday),
139
- ("day", self.day),
140
- ("day_period", self.day_period),
141
- ("hour", self.hour),
142
- ("minute", self.minute),
143
- ("second", self.second),
144
- ("fraction_second_digits", self.fraction_second_digits),
145
- ("time_zone_name", self.time_zone_name),
146
- )
147
- if v is not None
148
- }
149
-
150
-
151
- OPTIONS_TO_SKELETON: OptionsToSkeletonT = {
152
- "era": {"short": "G", "long": "GGGG", "narrow": "GGGGG"},
153
- "year": {"numeric": ("yyyy", "y"), "2-digit": "yy"},
154
- "month": {"numeric": "M", "2-digit": "MM", "short": "MMM", "long": "MMMM", "narrow": "MMMMM"},
155
- "weekday": {"short": "E", "long": "EEEE", "narrow": "EEEEE"},
156
- "day": {"numeric": "d", "2-digit": "dd"},
157
- "day_period": {
158
- "short": ("a", "b", "B"),
159
- "long": ("aaaa", "bbbb", "BBBB"),
160
- "narrow": ("aaaaa", "bbbbb", "BBBBB"),
161
- },
162
- "hour": {"numeric": ("j", "H", "h"), "2-digit": ("jj", "HH", "hh")},
163
- "minute": {"numeric": "m", "2-digit": "mm"},
164
- "second": {"numeric": "s", "2-digit": "ss"},
165
- "fraction_second_digits": {1: "S", 2: "SS", 3: "SSS"},
166
- "time_zone_name": {
167
- "short": "z",
168
- "long": "zzzz",
169
- "short_offset": "Z",
170
- "long_offset": "ZZZZ",
171
- "short_generic": "v",
172
- "long_generic": "vvvv",
173
- },
174
- }
175
-
176
-
177
- @overload
178
- def _option_to_skeleton_bit(
179
- field: Literal["era"],
180
- format: EraFormatT,
181
- ) -> EraPatternT | tuple[EraPatternT, ...]: ...
182
- @overload
183
- def _option_to_skeleton_bit(
184
- field: Literal["year"],
185
- format: YearFormatT,
186
- ) -> YearPatternT | tuple[YearPatternT, ...]: ...
187
- @overload
188
- def _option_to_skeleton_bit(
189
- field: Literal["month"],
190
- format: MonthFormatT,
191
- ) -> MonthPatternT | tuple[MonthPatternT, ...]: ...
192
- @overload
193
- def _option_to_skeleton_bit(
194
- field: Literal["weekday"],
195
- format: WeekdayFormatT,
196
- ) -> WeekdayPatternT | tuple[WeekdayPatternT, ...]: ...
197
- @overload
198
- def _option_to_skeleton_bit(
199
- field: Literal["day"],
200
- format: DayFormatT,
201
- ) -> DayPatternT | tuple[DayPatternT, ...]: ...
202
- @overload
203
- def _option_to_skeleton_bit(
204
- field: Literal["day_period"],
205
- format: DayPeriodFormatT,
206
- ) -> DayPeriodPatternT | tuple[DayPeriodPatternT, ...]: ...
207
- @overload
208
- def _option_to_skeleton_bit(
209
- field: Literal["hour"],
210
- format: HourFormatT,
211
- ) -> HourPatternT | tuple[HourPatternT, ...]: ...
212
- @overload
213
- def _option_to_skeleton_bit(
214
- field: Literal["minute"],
215
- format: MinuteFormatT,
216
- ) -> MinutePatternT | tuple[MinutePatternT, ...]: ...
217
- @overload
218
- def _option_to_skeleton_bit(
219
- field: Literal["second"],
220
- format: SecondFormatT,
221
- ) -> SecondPatternT | tuple[SecondPatternT, ...]: ...
222
- @overload
223
- def _option_to_skeleton_bit(
224
- field: Literal["fraction_second_digits"],
225
- format: FractionSecondDigitsFormatT,
226
- ) -> FractionSecondDigitsPatternT | tuple[FractionSecondDigitsPatternT, ...]: ...
227
- @overload
228
- def _option_to_skeleton_bit(
229
- field: Literal["time_zone_name"],
230
- format: TimezoneNameFormatT,
231
- ) -> TimezoneNamePatternT | tuple[TimezoneNamePatternT, ...]: ...
232
- def _option_to_skeleton_bit(
233
- field,
234
- format,
235
- ):
236
- return OPTIONS_TO_SKELETON[field][format]
237
-
238
-
239
- def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[str]:
240
- datetime_code_bits: list[str | tuple[str, ...]] = []
241
-
242
- # For order see babel.dates.PATTERN_CHAR_ORDER
243
- if options.era:
244
- datetime_code_bits.append(_option_to_skeleton_bit("era", options.era))
245
- if options.year:
246
- datetime_code_bits.append(_option_to_skeleton_bit("year", options.year))
247
- if options.month:
248
- datetime_code_bits.append(_option_to_skeleton_bit("month", options.month))
249
- if options.weekday:
250
- datetime_code_bits.append(_option_to_skeleton_bit("weekday", options.weekday))
251
- if options.day:
252
- datetime_code_bits.append(_option_to_skeleton_bit("day", options.day))
253
- if options.day_period:
254
- datetime_code_bits.append(_option_to_skeleton_bit("day_period", options.day_period))
255
- if options.hour:
256
- datetime_code_bits.append(_option_to_skeleton_bit("hour", options.hour))
257
- if options.minute:
258
- datetime_code_bits.append(_option_to_skeleton_bit("minute", options.minute))
259
- if options.second:
260
- datetime_code_bits.append(_option_to_skeleton_bit("second", options.second))
261
- if options.fraction_second_digits:
262
- datetime_code_bits.append(
263
- _option_to_skeleton_bit("fraction_second_digits", options.fraction_second_digits),
264
- )
265
- if options.time_zone_name:
266
- datetime_code_bits.append(_option_to_skeleton_bit("time_zone_name", options.time_zone_name))
267
-
268
- def generate_skeletons(prefix: str, remaining: list[str | tuple[str, ...]]) -> Iterable[str]:
269
- if not remaining:
270
- yield prefix
271
- return
272
-
273
- next_bit = remaining[0]
274
- if isinstance(next_bit, tuple):
275
- for next_bit_variant in next_bit:
276
- yield from generate_skeletons(prefix + next_bit_variant, remaining[1:])
277
- else:
278
- yield from generate_skeletons(prefix + next_bit, remaining[1:])
279
-
280
- yield from generate_skeletons("", datetime_code_bits)
281
-
282
-
283
- @dataclasses.dataclass(frozen=True, kw_only=True)
284
- class MatchedFormatPattern:
285
- skeleton: str
286
- pattern: str
287
-
288
- def __str__(self) -> str:
289
- return self.pattern
290
-
291
-
292
- class FormatPatternNotFoundException(Exception):
293
- pass
294
-
295
-
296
- @cache
297
- def _options_to_format_pattern(
298
- locale: icu.Locale, # ty: ignore[unresolved-attribute]
299
- options: DateTimeFormatOptions,
300
- ) -> MatchedFormatPattern:
301
- possible_skeletons = list(_options_to_possible_skeletons(options))
302
-
303
- generator = icu.DateTimePatternGenerator.createInstance(locale) # ty: ignore[unresolved-attribute]
304
-
305
- # Try a perfect match
306
- for skeleton in possible_skeletons:
307
- pattern = generator.getPatternForSkeleton(skeleton)
308
- if pattern:
309
- return MatchedFormatPattern(
310
- skeleton=skeleton,
311
- pattern=pattern,
312
- )
313
-
314
- # Try to find best match
315
- for skeleton in possible_skeletons:
316
- pattern = generator.getBestPattern(skeleton)
317
- if pattern:
318
- return MatchedFormatPattern(
319
- skeleton=skeleton,
320
- pattern=pattern,
321
- )
322
-
323
- raise FormatPatternNotFoundException("Didn't find pattern for desired options")
324
-
325
-
326
- class DateTimeFormat:
327
- locale: str
328
- options: DateTimeFormatOptions
329
-
330
- def __init__(
331
- self,
332
- locale: str,
333
- options: DateTimeFormatOptions | DateTimeFormatOptionsDictT,
334
- ) -> None:
335
- self.locale = locale
336
- if isinstance(options, DateTimeFormatOptions):
337
- self.options = options
338
- else:
339
- self.options = DateTimeFormatOptions(**options)
340
-
341
- @cached_property
342
- def icu_locale(self) -> icu.Locale: # ty: ignore[unresolved-attribute]
343
- return icu.Locale(self.locale) # ty: ignore[unresolved-attribute]
344
-
345
- @cached_property
346
- def matched_pattern(self) -> MatchedFormatPattern:
347
- return _options_to_format_pattern(self.icu_locale, self.options)
348
-
349
- @cached_property
350
- def icu_pattern(self) -> str:
351
- return self.matched_pattern.pattern
352
-
353
- @cached_property
354
- def icu_date_format(self) -> icu.SimpleDateFormat: # ty: ignore[unresolved-attribute]
355
- return icu.SimpleDateFormat(self.icu_pattern, self.icu_locale) # ty: ignore[unresolved-attribute]
356
-
357
- def format(self, datetime_: dt.datetime, /) -> str:
358
- return self.icu_date_format.format(datetime_)
File without changes
File without changes