python-intl 0.1.0__tar.gz → 0.3.1__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.
- python_intl-0.3.1/PKG-INFO +86 -0
- python_intl-0.3.1/README.md +73 -0
- {python_intl-0.1.0 → python_intl-0.3.1}/pyproject.toml +6 -2
- {python_intl-0.1.0 → python_intl-0.3.1}/pyproject.toml.orig +6 -2
- python_intl-0.3.1/python_intl/__init__.py +6 -0
- python_intl-0.3.1/python_intl/datetimeformat.py +433 -0
- python_intl-0.1.0/PKG-INFO +0 -42
- python_intl-0.1.0/README.md +0 -29
- python_intl-0.1.0/python_intl/__init__.py +0 -1
- python_intl-0.1.0/python_intl/datetimeformat.py +0 -358
- {python_intl-0.1.0 → python_intl-0.3.1}/LICENSE +0 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-intl
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Python implementation of the Intl JavaScript API
|
|
5
|
+
Author: David Danier
|
|
6
|
+
Author-email: David Danier <david.danier@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: pyicu>=2.16.2
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Project-URL: Repository, https://github.com/ddanier/python-intl
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# `python-intl`
|
|
15
|
+
|
|
16
|
+
A small library using [PyICU](https://pypi.org/project/pyicu/) to provide a Python
|
|
17
|
+
API similar to what the [`Intl` JavaScript API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)
|
|
18
|
+
provides. It is not meant to fully behave the same, but instead be close enough so
|
|
19
|
+
the "same" code works on JavaScript and Python, with similar results.
|
|
20
|
+
|
|
21
|
+
**Status:** This is very much work in progress. Currently only `Intl.DateTimeFormat`
|
|
22
|
+
exists and this also is not complete yet.
|
|
23
|
+
|
|
24
|
+
## General notes about the Python adaption
|
|
25
|
+
|
|
26
|
+
All names will be using the Python style rules. This means instead of
|
|
27
|
+
`formatToParts` a method will be called `format_to_parts`. Also a dictionary
|
|
28
|
+
key like `dayPeriod` will be named `day_period`. Python uses snake case, let's
|
|
29
|
+
stick to this.
|
|
30
|
+
|
|
31
|
+
Instead of passing around undefined objects like in JavaScript we want to use
|
|
32
|
+
well defined and typed dataclasses. This for example is true for the
|
|
33
|
+
`Intl.DateTimeFormat` format options, you can use `DateTimeFormatOptions` as
|
|
34
|
+
a clean representation of those. Using a dictionary (which behaves the most
|
|
35
|
+
like those JavaScript objects) is still fine and will automatically converted,
|
|
36
|
+
as seen in the examples here.
|
|
37
|
+
|
|
38
|
+
Many objects like for example the `DateTimeFormatOptions` provide methods to
|
|
39
|
+
convert their Python representation to a JavaScript compatible JSON format
|
|
40
|
+
by returning a `dict` using the JavaScript naming. You can use the `to_json`
|
|
41
|
+
method for this.
|
|
42
|
+
|
|
43
|
+
For example:
|
|
44
|
+
```python
|
|
45
|
+
import python_intl as Intl
|
|
46
|
+
|
|
47
|
+
Intl.DateTimeFormatOptions(time_zone_name="short_offset").to_json()
|
|
48
|
+
# Will return: {'timeZoneName': 'shortOffset'}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Available `Intl` classes
|
|
52
|
+
|
|
53
|
+
### `Intl.DateTimeFormat`
|
|
54
|
+
|
|
55
|
+
#### Example usage
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import datetime
|
|
59
|
+
import python_intl as Intl
|
|
60
|
+
|
|
61
|
+
datetime_ = datetime.datetime(2026, 8, 15)
|
|
62
|
+
formatter = Intl.DateTimeFormat("de-DE", {"year": "numeric", "month": "2-digit", "day": "2-digit"})
|
|
63
|
+
formatter.format(datetime_) # Will output the German format: "15.08.2026"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
#### Compatibility
|
|
67
|
+
|
|
68
|
+
| Method | Status | Python name |
|
|
69
|
+
| ----------------------------------- | :----: | -------------------------------- |
|
|
70
|
+
| `DateTimeFormat.format` | ✅ | |
|
|
71
|
+
| `DateTimeFormat.formatToParts` | ✅ | `DateTimeFormat.format_to_parts` |
|
|
72
|
+
| `DateTimeFormat.supportedLocalesOf` | ❌ | |
|
|
73
|
+
| `DateTimeFormat.formatRange` | ❌ | |
|
|
74
|
+
| `DateTimeFormat.formatRangeToParts` | ❌ | |
|
|
75
|
+
| `DateTimeFormat.resolvedOptions` | ❌ | |
|
|
76
|
+
|
|
77
|
+
## Installation
|
|
78
|
+
|
|
79
|
+
Be sure to be able to install `PyICU`, see the installation docs there:
|
|
80
|
+
https://gitlab.pyicu.org/main/pyicu#installing-pyicu
|
|
81
|
+
|
|
82
|
+
**Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
|
|
83
|
+
setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
|
|
84
|
+
|
|
85
|
+
When this is done you should be able to install `python-intl` using any package
|
|
86
|
+
manager, like `pip install python-intl` or `uv add python-intl`.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# `python-intl`
|
|
2
|
+
|
|
3
|
+
A small library using [PyICU](https://pypi.org/project/pyicu/) to provide a Python
|
|
4
|
+
API similar to what the [`Intl` JavaScript API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)
|
|
5
|
+
provides. It is not meant to fully behave the same, but instead be close enough so
|
|
6
|
+
the "same" code works on JavaScript and Python, with similar results.
|
|
7
|
+
|
|
8
|
+
**Status:** This is very much work in progress. Currently only `Intl.DateTimeFormat`
|
|
9
|
+
exists and this also is not complete yet.
|
|
10
|
+
|
|
11
|
+
## General notes about the Python adaption
|
|
12
|
+
|
|
13
|
+
All names will be using the Python style rules. This means instead of
|
|
14
|
+
`formatToParts` a method will be called `format_to_parts`. Also a dictionary
|
|
15
|
+
key like `dayPeriod` will be named `day_period`. Python uses snake case, let's
|
|
16
|
+
stick to this.
|
|
17
|
+
|
|
18
|
+
Instead of passing around undefined objects like in JavaScript we want to use
|
|
19
|
+
well defined and typed dataclasses. This for example is true for the
|
|
20
|
+
`Intl.DateTimeFormat` format options, you can use `DateTimeFormatOptions` as
|
|
21
|
+
a clean representation of those. Using a dictionary (which behaves the most
|
|
22
|
+
like those JavaScript objects) is still fine and will automatically converted,
|
|
23
|
+
as seen in the examples here.
|
|
24
|
+
|
|
25
|
+
Many objects like for example the `DateTimeFormatOptions` provide methods to
|
|
26
|
+
convert their Python representation to a JavaScript compatible JSON format
|
|
27
|
+
by returning a `dict` using the JavaScript naming. You can use the `to_json`
|
|
28
|
+
method for this.
|
|
29
|
+
|
|
30
|
+
For example:
|
|
31
|
+
```python
|
|
32
|
+
import python_intl as Intl
|
|
33
|
+
|
|
34
|
+
Intl.DateTimeFormatOptions(time_zone_name="short_offset").to_json()
|
|
35
|
+
# Will return: {'timeZoneName': 'shortOffset'}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Available `Intl` classes
|
|
39
|
+
|
|
40
|
+
### `Intl.DateTimeFormat`
|
|
41
|
+
|
|
42
|
+
#### Example usage
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import datetime
|
|
46
|
+
import python_intl as Intl
|
|
47
|
+
|
|
48
|
+
datetime_ = datetime.datetime(2026, 8, 15)
|
|
49
|
+
formatter = Intl.DateTimeFormat("de-DE", {"year": "numeric", "month": "2-digit", "day": "2-digit"})
|
|
50
|
+
formatter.format(datetime_) # Will output the German format: "15.08.2026"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
#### Compatibility
|
|
54
|
+
|
|
55
|
+
| Method | Status | Python name |
|
|
56
|
+
| ----------------------------------- | :----: | -------------------------------- |
|
|
57
|
+
| `DateTimeFormat.format` | ✅ | |
|
|
58
|
+
| `DateTimeFormat.formatToParts` | ✅ | `DateTimeFormat.format_to_parts` |
|
|
59
|
+
| `DateTimeFormat.supportedLocalesOf` | ❌ | |
|
|
60
|
+
| `DateTimeFormat.formatRange` | ❌ | |
|
|
61
|
+
| `DateTimeFormat.formatRangeToParts` | ❌ | |
|
|
62
|
+
| `DateTimeFormat.resolvedOptions` | ❌ | |
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
Be sure to be able to install `PyICU`, see the installation docs there:
|
|
67
|
+
https://gitlab.pyicu.org/main/pyicu#installing-pyicu
|
|
68
|
+
|
|
69
|
+
**Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
|
|
70
|
+
setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
|
|
71
|
+
|
|
72
|
+
When this is done you should be able to install `python-intl` using any package
|
|
73
|
+
manager, like `pip install python-intl` or `uv add python-intl`.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "python-intl"
|
|
3
|
-
version = "0.1
|
|
4
|
-
description = "
|
|
3
|
+
version = "0.3.1"
|
|
4
|
+
description = "Python implementation of the Intl JavaScript API"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
7
|
license-files = ["LICENSE"]
|
|
@@ -80,6 +80,10 @@ ignore = [
|
|
|
80
80
|
"F401",
|
|
81
81
|
]
|
|
82
82
|
|
|
83
|
+
[tool.ruff.lint.isort]
|
|
84
|
+
combine-as-imports = true
|
|
85
|
+
force-wrap-aliases = true
|
|
86
|
+
|
|
83
87
|
[tool.uv.build-backend]
|
|
84
88
|
module-name = "python_intl"
|
|
85
89
|
module-root = ""
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "python-intl"
|
|
3
|
-
version = "0.1
|
|
4
|
-
description = "
|
|
3
|
+
version = "0.3.1"
|
|
4
|
+
description = "Python implementation of the Intl JavaScript API"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [
|
|
7
7
|
{ name = "David Danier", email = "david.danier@gmail.com" }
|
|
@@ -46,6 +46,10 @@ ignore = ["A001","A002","A003","ANN401","C901","N8","B008","F405","F821"]
|
|
|
46
46
|
"conftest.py" = ["S101","ANN","F401"]
|
|
47
47
|
"test_*.py" = ["S101","ANN","F401"]
|
|
48
48
|
|
|
49
|
+
[tool.ruff.lint.isort]
|
|
50
|
+
combine-as-imports = true
|
|
51
|
+
force-wrap-aliases = true
|
|
52
|
+
|
|
49
53
|
[build-system]
|
|
50
54
|
requires = ["uv_build>=0.12.3,<0.13.0"]
|
|
51
55
|
build-backend = "uv_build"
|
|
@@ -0,0 +1,433 @@
|
|
|
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
|
+
type PatternPartTypeT = Literal[
|
|
53
|
+
"literal", "unknown",
|
|
54
|
+
"era", "year", "month", "weekday", "day", "day_period",
|
|
55
|
+
"hour", "minute", "second", "fraction_second_digits",
|
|
56
|
+
"time_zone_name",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
# Important: Must be the same as DateTimeFormatOptions
|
|
60
|
+
# (nothing is required, as this will be used to construct a
|
|
61
|
+
# DateTimeFormatOptions instance, so default values apply then)
|
|
62
|
+
class DateTimeFormatOptionsDictT(TypedDict):
|
|
63
|
+
locale_matcher: NotRequired[LocaleMatcherT]
|
|
64
|
+
hour12: NotRequired[Hour12T]
|
|
65
|
+
hour_cycle: NotRequired[HourCycleT]
|
|
66
|
+
|
|
67
|
+
era: NotRequired[EraFormatT]
|
|
68
|
+
year: NotRequired[YearFormatT]
|
|
69
|
+
month: NotRequired[MonthFormatT]
|
|
70
|
+
weekday: NotRequired[WeekdayFormatT]
|
|
71
|
+
day: NotRequired[DayFormatT]
|
|
72
|
+
day_period: NotRequired[DayPeriodFormatT]
|
|
73
|
+
hour: NotRequired[HourFormatT]
|
|
74
|
+
minute: NotRequired[MinuteFormatT]
|
|
75
|
+
second: NotRequired[SecondFormatT]
|
|
76
|
+
fraction_second_digits: NotRequired[FractionSecondDigitsFormatT]
|
|
77
|
+
time_zone_name: NotRequired[TimezoneNameFormatT]
|
|
78
|
+
|
|
79
|
+
_PATTERN_SYMBOLS = "GyYuUrQqMLqQdDFgEecabBhHkKmsSAzZOvVxX" # includes unused
|
|
80
|
+
_PATTERN_SYMBOL_TO_TYPE: dict[str, PatternPartTypeT] = {
|
|
81
|
+
"G": "era",
|
|
82
|
+
"y": "year",
|
|
83
|
+
"Y": "year",
|
|
84
|
+
"u": "year",
|
|
85
|
+
"U": "year",
|
|
86
|
+
"r": "year",
|
|
87
|
+
"M": "month",
|
|
88
|
+
"E": "weekday",
|
|
89
|
+
"e": "weekday",
|
|
90
|
+
"c": "weekday",
|
|
91
|
+
"d": "day",
|
|
92
|
+
"a": "day_period",
|
|
93
|
+
"b": "day_period",
|
|
94
|
+
"C": "day_period",
|
|
95
|
+
"h": "hour",
|
|
96
|
+
"H": "hour",
|
|
97
|
+
"k": "hour",
|
|
98
|
+
"K": "hour",
|
|
99
|
+
"m": "minute",
|
|
100
|
+
"s": "second",
|
|
101
|
+
"S": "fraction_second_digits",
|
|
102
|
+
"z": "time_zone_name",
|
|
103
|
+
"Z": "time_zone_name",
|
|
104
|
+
"O": "time_zone_name",
|
|
105
|
+
"v": "time_zone_name",
|
|
106
|
+
"V": "time_zone_name",
|
|
107
|
+
"x": "time_zone_name",
|
|
108
|
+
"X": "time_zone_name",
|
|
109
|
+
}
|
|
110
|
+
_PATTERN_QUOTE = "'"
|
|
111
|
+
|
|
112
|
+
_COMPONENT_TO_JSON_MAP: dict[str, str] = {
|
|
113
|
+
"day_period": "dayPeriod",
|
|
114
|
+
"fraction_second_digits": "fractionalSecondDigits",
|
|
115
|
+
"time_zone_name": "timeZoneName",
|
|
116
|
+
}
|
|
117
|
+
_TIMEZONE_NAME_TO_JSON_MAP: dict[str | None, str] = {
|
|
118
|
+
"short_offset": "shortOffset",
|
|
119
|
+
"long_offset": "longOffset",
|
|
120
|
+
"short_generic": "shortGeneric",
|
|
121
|
+
"long_generic": "longGeneric",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
|
|
126
|
+
class DateTimeFormatOptions:
|
|
127
|
+
locale_matcher: LocaleMatcherT = "best fit"
|
|
128
|
+
hour12: Hour12T = None
|
|
129
|
+
hour_cycle: HourCycleT = None
|
|
130
|
+
|
|
131
|
+
era: EraFormatT | None = None
|
|
132
|
+
year: YearFormatT | None = None
|
|
133
|
+
month: MonthFormatT | None = None
|
|
134
|
+
weekday: WeekdayFormatT | None = None
|
|
135
|
+
day: DayFormatT | None = None
|
|
136
|
+
day_period: DayPeriodFormatT | None = None
|
|
137
|
+
hour: HourFormatT | None = None
|
|
138
|
+
minute: MinuteFormatT | None = None
|
|
139
|
+
second: SecondFormatT | None = None
|
|
140
|
+
fraction_second_digits: FractionSecondDigitsFormatT | None = None
|
|
141
|
+
time_zone_name: TimezoneNameFormatT | None = None
|
|
142
|
+
|
|
143
|
+
def to_json(self) -> dict[str, str | int]:
|
|
144
|
+
return {
|
|
145
|
+
k: v
|
|
146
|
+
for k, v in (
|
|
147
|
+
("era", self.era),
|
|
148
|
+
("year", self.year),
|
|
149
|
+
("month", self.month),
|
|
150
|
+
("weekday", self.weekday),
|
|
151
|
+
("day", self.day),
|
|
152
|
+
("dayPeriod", self.day_period),
|
|
153
|
+
("hour", self.hour),
|
|
154
|
+
("minute", self.minute),
|
|
155
|
+
("second", self.second),
|
|
156
|
+
("fractionalSecondDigits", self.fraction_second_digits),
|
|
157
|
+
("timeZoneName", _TIMEZONE_NAME_TO_JSON_MAP.get(self.time_zone_name, self.time_zone_name)),
|
|
158
|
+
)
|
|
159
|
+
if v is not None
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[str]:
|
|
164
|
+
skeleton_parts: list[str | tuple[str, ...]] = []
|
|
165
|
+
|
|
166
|
+
# Note: The parts should be ordered from big to small.
|
|
167
|
+
|
|
168
|
+
match options.era:
|
|
169
|
+
case "short":
|
|
170
|
+
skeleton_parts.append("G")
|
|
171
|
+
case "long":
|
|
172
|
+
skeleton_parts.append("GGGG")
|
|
173
|
+
case "narrow":
|
|
174
|
+
skeleton_parts.append("GGGGG")
|
|
175
|
+
|
|
176
|
+
match options.year:
|
|
177
|
+
case "numeric":
|
|
178
|
+
skeleton_parts.append(("yyyy", "y"))
|
|
179
|
+
case "2-digit":
|
|
180
|
+
skeleton_parts.append("yy")
|
|
181
|
+
|
|
182
|
+
match options.month:
|
|
183
|
+
case "numeric":
|
|
184
|
+
skeleton_parts.append("M")
|
|
185
|
+
case "2-digit":
|
|
186
|
+
skeleton_parts.append("MM")
|
|
187
|
+
case "short":
|
|
188
|
+
skeleton_parts.append("MMM")
|
|
189
|
+
case "long":
|
|
190
|
+
skeleton_parts.append("MMMM")
|
|
191
|
+
case "narrow":
|
|
192
|
+
skeleton_parts.append("MMMMM")
|
|
193
|
+
|
|
194
|
+
match options.weekday:
|
|
195
|
+
case "short":
|
|
196
|
+
skeleton_parts.append("E")
|
|
197
|
+
case "long":
|
|
198
|
+
skeleton_parts.append("EEEE")
|
|
199
|
+
case "narrow":
|
|
200
|
+
skeleton_parts.append("EEEEE")
|
|
201
|
+
|
|
202
|
+
match options.day:
|
|
203
|
+
case "numeric":
|
|
204
|
+
skeleton_parts.append("d")
|
|
205
|
+
case "2-digit":
|
|
206
|
+
skeleton_parts.append("dd")
|
|
207
|
+
|
|
208
|
+
match options.day_period:
|
|
209
|
+
case "short":
|
|
210
|
+
skeleton_parts.append("B")
|
|
211
|
+
case "long":
|
|
212
|
+
skeleton_parts.append("BBBB")
|
|
213
|
+
case "narrow":
|
|
214
|
+
skeleton_parts.append("BBBBB")
|
|
215
|
+
|
|
216
|
+
match (options.hour_cycle, options.hour12, options.hour):
|
|
217
|
+
case ("h11", _, "numeric"):
|
|
218
|
+
skeleton_parts.append(("aK", "K"))
|
|
219
|
+
case ("h11", _, "2-digit"):
|
|
220
|
+
skeleton_parts.append(("aKK", "KK"))
|
|
221
|
+
case ("h12", _, "numeric"):
|
|
222
|
+
skeleton_parts.append(("ah", "h"))
|
|
223
|
+
case ("h12", _, "2-digit"):
|
|
224
|
+
skeleton_parts.append(("ahh", "hh"))
|
|
225
|
+
case ("h23", _, "numeric"):
|
|
226
|
+
skeleton_parts.append("H")
|
|
227
|
+
case ("h23", _, "2-digit"):
|
|
228
|
+
skeleton_parts.append("HH")
|
|
229
|
+
case ("h24", _, "numeric"):
|
|
230
|
+
skeleton_parts.append("k")
|
|
231
|
+
case ("h24", _, "2-digit"):
|
|
232
|
+
skeleton_parts.append("kk")
|
|
233
|
+
case (_, True, "numeric"):
|
|
234
|
+
skeleton_parts.append(("ah", "h"))
|
|
235
|
+
case (_, True, "2-digit"):
|
|
236
|
+
skeleton_parts.append(("ahh", "hh"))
|
|
237
|
+
case (_, False, "numeric"):
|
|
238
|
+
skeleton_parts.append("H")
|
|
239
|
+
case (_, False, "2-digit"):
|
|
240
|
+
skeleton_parts.append("HH")
|
|
241
|
+
case (_, _, "numeric"):
|
|
242
|
+
skeleton_parts.append("j")
|
|
243
|
+
case (_, _, "2-digit"):
|
|
244
|
+
skeleton_parts.append(("jj", "j"))
|
|
245
|
+
|
|
246
|
+
match options.minute:
|
|
247
|
+
case "numeric":
|
|
248
|
+
skeleton_parts.append("m")
|
|
249
|
+
case "2-digit":
|
|
250
|
+
skeleton_parts.append("mm")
|
|
251
|
+
|
|
252
|
+
match options.second:
|
|
253
|
+
case "numeric":
|
|
254
|
+
skeleton_parts.append("s")
|
|
255
|
+
case "2-digit":
|
|
256
|
+
skeleton_parts.append("ss")
|
|
257
|
+
|
|
258
|
+
if options.fraction_second_digits:
|
|
259
|
+
skeleton_parts.append("S" * options.fraction_second_digits)
|
|
260
|
+
|
|
261
|
+
match options.time_zone_name:
|
|
262
|
+
case "short":
|
|
263
|
+
skeleton_parts.append("z")
|
|
264
|
+
case "long":
|
|
265
|
+
skeleton_parts.append("zzzz")
|
|
266
|
+
case "short_offset":
|
|
267
|
+
skeleton_parts.append("Z")
|
|
268
|
+
case "long_offset":
|
|
269
|
+
skeleton_parts.append("ZZZZ")
|
|
270
|
+
case "short_generic":
|
|
271
|
+
skeleton_parts.append("v")
|
|
272
|
+
case "long_generic":
|
|
273
|
+
skeleton_parts.append("vvvv")
|
|
274
|
+
|
|
275
|
+
def generate_skeletons(prefix: str, remaining: list[str | tuple[str, ...]]) -> Iterable[str]:
|
|
276
|
+
if not remaining:
|
|
277
|
+
yield prefix
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
next_bit = remaining[0]
|
|
281
|
+
if isinstance(next_bit, tuple):
|
|
282
|
+
for next_bit_variant in next_bit:
|
|
283
|
+
yield from generate_skeletons(prefix + next_bit_variant, remaining[1:])
|
|
284
|
+
else:
|
|
285
|
+
yield from generate_skeletons(prefix + next_bit, remaining[1:])
|
|
286
|
+
|
|
287
|
+
yield from generate_skeletons("", skeleton_parts)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
|
|
291
|
+
class _MatchedFormatPattern:
|
|
292
|
+
skeleton: str
|
|
293
|
+
pattern: str
|
|
294
|
+
|
|
295
|
+
def __str__(self) -> str:
|
|
296
|
+
return self.pattern
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class FormatPatternNotFoundException(Exception):
|
|
300
|
+
pass
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
|
|
304
|
+
class DateTimePatternPart:
|
|
305
|
+
type: PatternPartTypeT
|
|
306
|
+
value: str
|
|
307
|
+
_pattern: str | None = None
|
|
308
|
+
|
|
309
|
+
def to_json(self) -> dict[str, str]:
|
|
310
|
+
return {
|
|
311
|
+
"type": _COMPONENT_TO_JSON_MAP.get(self.type, self.type),
|
|
312
|
+
"value": self.value,
|
|
313
|
+
# note: _pattern is internal and not available in JavaScript
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@cache
|
|
318
|
+
def _options_to_format_pattern(
|
|
319
|
+
locale: icu.Locale, # ty: ignore[unresolved-attribute]
|
|
320
|
+
options: DateTimeFormatOptions,
|
|
321
|
+
) -> _MatchedFormatPattern:
|
|
322
|
+
possible_skeletons = list(_options_to_possible_skeletons(options))
|
|
323
|
+
|
|
324
|
+
generator = icu.DateTimePatternGenerator.createInstance(locale) # ty: ignore[unresolved-attribute]
|
|
325
|
+
|
|
326
|
+
# Try a perfect match
|
|
327
|
+
for skeleton in possible_skeletons:
|
|
328
|
+
pattern = generator.getPatternForSkeleton(skeleton)
|
|
329
|
+
if pattern:
|
|
330
|
+
return _MatchedFormatPattern(
|
|
331
|
+
skeleton=skeleton,
|
|
332
|
+
pattern=pattern,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
# Try to find best match
|
|
336
|
+
if options.locale_matcher == "best fit":
|
|
337
|
+
for skeleton in possible_skeletons:
|
|
338
|
+
pattern = generator.getBestPattern(skeleton)
|
|
339
|
+
if pattern:
|
|
340
|
+
return _MatchedFormatPattern(
|
|
341
|
+
skeleton=skeleton,
|
|
342
|
+
pattern=pattern,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
raise FormatPatternNotFoundException("Didn't find pattern for desired options")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class DateTimeFormat:
|
|
349
|
+
locale: str
|
|
350
|
+
options: DateTimeFormatOptions
|
|
351
|
+
|
|
352
|
+
def __init__(
|
|
353
|
+
self,
|
|
354
|
+
locale: str,
|
|
355
|
+
options: DateTimeFormatOptions | DateTimeFormatOptionsDictT,
|
|
356
|
+
) -> None:
|
|
357
|
+
self.locale = locale
|
|
358
|
+
if isinstance(options, DateTimeFormatOptions):
|
|
359
|
+
self.options = options
|
|
360
|
+
else:
|
|
361
|
+
self.options = DateTimeFormatOptions(**options)
|
|
362
|
+
|
|
363
|
+
@cached_property
|
|
364
|
+
def _icu_locale(self) -> icu.Locale: # ty: ignore[unresolved-attribute]
|
|
365
|
+
return icu.Locale(self.locale) # ty: ignore[unresolved-attribute]
|
|
366
|
+
|
|
367
|
+
@cached_property
|
|
368
|
+
def _matched_pattern(self) -> _MatchedFormatPattern:
|
|
369
|
+
return _options_to_format_pattern(self._icu_locale, self.options)
|
|
370
|
+
|
|
371
|
+
@cached_property
|
|
372
|
+
def _icu_pattern(self) -> str:
|
|
373
|
+
return self._matched_pattern.pattern
|
|
374
|
+
|
|
375
|
+
@cached_property
|
|
376
|
+
def _icu_date_format(self) -> icu.SimpleDateFormat: # ty: ignore[unresolved-attribute]
|
|
377
|
+
return icu.SimpleDateFormat(self._icu_pattern, self._icu_locale) # ty: ignore[unresolved-attribute]
|
|
378
|
+
|
|
379
|
+
def format(self, datetime_: dt.datetime, /) -> str:
|
|
380
|
+
return self._icu_date_format.format(datetime_)
|
|
381
|
+
|
|
382
|
+
def format_to_parts(self, datetime_: dt.datetime, /) -> Iterable[DateTimePatternPart]:
|
|
383
|
+
# Based on https://github.com/unicode-org/icu/blob/6fb634d81d10dd4667fb3fbcd1f19d9b9b926e62/icu4c/source/i18n/smpdtfmt.cpp#L1060
|
|
384
|
+
pattern = self._icu_pattern
|
|
385
|
+
in_quote = False
|
|
386
|
+
prev_char = ""
|
|
387
|
+
pattern_length = len(pattern)
|
|
388
|
+
count = 0
|
|
389
|
+
i = 0
|
|
390
|
+
literal_chars: list[str] = []
|
|
391
|
+
while i < pattern_length:
|
|
392
|
+
char = pattern[i]
|
|
393
|
+
|
|
394
|
+
if char != prev_char and count > 0:
|
|
395
|
+
yield DateTimePatternPart(
|
|
396
|
+
type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
|
|
397
|
+
value=icu.SimpleDateFormat(prev_char * count, self._icu_locale).format(datetime_), # ty: ignore[unresolved-attribute]
|
|
398
|
+
_pattern=prev_char * count,
|
|
399
|
+
)
|
|
400
|
+
count = 0
|
|
401
|
+
|
|
402
|
+
if char == _PATTERN_QUOTE:
|
|
403
|
+
if (i + 1) < pattern_length and pattern[i + 1] == _PATTERN_QUOTE:
|
|
404
|
+
literal_chars.append(_PATTERN_QUOTE)
|
|
405
|
+
i += 1
|
|
406
|
+
else:
|
|
407
|
+
in_quote = not in_quote
|
|
408
|
+
elif not in_quote and char in _PATTERN_SYMBOLS:
|
|
409
|
+
if literal_chars:
|
|
410
|
+
yield DateTimePatternPart(
|
|
411
|
+
type="literal",
|
|
412
|
+
value="".join(literal_chars),
|
|
413
|
+
)
|
|
414
|
+
literal_chars = []
|
|
415
|
+
prev_char = char
|
|
416
|
+
count += 1
|
|
417
|
+
else:
|
|
418
|
+
literal_chars.append(char)
|
|
419
|
+
|
|
420
|
+
i += 1
|
|
421
|
+
|
|
422
|
+
if count > 0:
|
|
423
|
+
yield DateTimePatternPart(
|
|
424
|
+
type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
|
|
425
|
+
value=icu.SimpleDateFormat(prev_char * count, self._icu_locale).format(datetime_), # ty: ignore[unresolved-attribute]
|
|
426
|
+
_pattern=prev_char * count,
|
|
427
|
+
)
|
|
428
|
+
assert not literal_chars # noqa: S101
|
|
429
|
+
elif literal_chars:
|
|
430
|
+
yield DateTimePatternPart(
|
|
431
|
+
type="literal",
|
|
432
|
+
value="".join(literal_chars),
|
|
433
|
+
)
|
python_intl-0.1.0/PKG-INFO
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: python-intl
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: Add your description here
|
|
5
|
-
Author: David Danier
|
|
6
|
-
Author-email: David Danier <david.danier@gmail.com>
|
|
7
|
-
License-Expression: MIT
|
|
8
|
-
License-File: LICENSE
|
|
9
|
-
Requires-Dist: pyicu>=2.16.2
|
|
10
|
-
Requires-Python: >=3.12
|
|
11
|
-
Project-URL: Repository, https://github.com/ddanier/python-intl
|
|
12
|
-
Description-Content-Type: text/markdown
|
|
13
|
-
|
|
14
|
-
# `python-intl`
|
|
15
|
-
|
|
16
|
-
A small library using [PyICU](https://pypi.org/project/pyicu/) to provide a Python
|
|
17
|
-
API similar to what the [`Intl` JavaScript API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)
|
|
18
|
-
provides.
|
|
19
|
-
|
|
20
|
-
**Status:** This is very much work in progress. Currently only `Intl.DateTimeFormat`
|
|
21
|
-
exists and this also is not complete yet.
|
|
22
|
-
|
|
23
|
-
## `Intl.DateTimeFormat`
|
|
24
|
-
|
|
25
|
-
### Example usage
|
|
26
|
-
|
|
27
|
-
```python
|
|
28
|
-
import datetime
|
|
29
|
-
from python_intl import DateTimeFormat
|
|
30
|
-
|
|
31
|
-
datetime_ = datetime.datetime(2026, 8, 15)
|
|
32
|
-
formatter = DateTimeFormat("de-DE", {"year": "numeric", "month": "2-digit", "day": "2-digit"})
|
|
33
|
-
formatter.format(datetime_) # Will output the German format: "15.08.2026"
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
## Installation
|
|
37
|
-
|
|
38
|
-
Be sure to be able to install `PyICU`, see the installation docs there:
|
|
39
|
-
https://gitlab.pyicu.org/main/pyicu#installing-pyicu
|
|
40
|
-
|
|
41
|
-
**Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
|
|
42
|
-
setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
|
python_intl-0.1.0/README.md
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
# `python-intl`
|
|
2
|
-
|
|
3
|
-
A small library using [PyICU](https://pypi.org/project/pyicu/) to provide a Python
|
|
4
|
-
API similar to what the [`Intl` JavaScript API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)
|
|
5
|
-
provides.
|
|
6
|
-
|
|
7
|
-
**Status:** This is very much work in progress. Currently only `Intl.DateTimeFormat`
|
|
8
|
-
exists and this also is not complete yet.
|
|
9
|
-
|
|
10
|
-
## `Intl.DateTimeFormat`
|
|
11
|
-
|
|
12
|
-
### Example usage
|
|
13
|
-
|
|
14
|
-
```python
|
|
15
|
-
import datetime
|
|
16
|
-
from python_intl import DateTimeFormat
|
|
17
|
-
|
|
18
|
-
datetime_ = datetime.datetime(2026, 8, 15)
|
|
19
|
-
formatter = DateTimeFormat("de-DE", {"year": "numeric", "month": "2-digit", "day": "2-digit"})
|
|
20
|
-
formatter.format(datetime_) # Will output the German format: "15.08.2026"
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
## Installation
|
|
24
|
-
|
|
25
|
-
Be sure to be able to install `PyICU`, see the installation docs there:
|
|
26
|
-
https://gitlab.pyicu.org/main/pyicu#installing-pyicu
|
|
27
|
-
|
|
28
|
-
**Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
|
|
29
|
-
setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
from .datetimeformat import DateTimeFormat as DateTimeFormat
|
|
@@ -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
|