Skip to content

Commit 339ba74

Browse files
committed
Preserve fixed-width year formatting tokens
1 parent e06dace commit 339ba74

3 files changed

Lines changed: 40 additions & 4 deletions

File tree

‎docs/docs/string_formatting.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,9 @@ The following tokens are currently supported:
106106

107107
| | Token | Output |
108108
| ------------------------------ | ------------- | ------------------------------------------ |
109-
| **Year** | YYYY | 2000, 2001, 2002 ... 2012, 2013 |
109+
| **Year** | YYYY | 0001, 0002 ... 2000, 2001 ... 9999 |
110110
| | YY | 00, 01, 02 ... 12, 13 |
111-
| | Y | 2000, 2001, 2002 ... 2012, 2013 |
111+
| | Y | 1, 2 ... 2000, 2001 ... 9999 |
112112
| **Quarter** | Q | 1 2 3 4 |
113113
| | Qo | 1st 2nd 3rd 4th |
114114
| **Month** | MMMM | January, February, March ... |

‎src/pendulum/formatting/formatter.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,8 @@ class Formatter:
9999

100100
_TOKENS_RULES: ClassVar[dict[str, Callable[[pendulum.DateTime], str]]] = {
101101
# Year
102-
"YYYY": lambda dt: f"{dt.year:d}",
103-
"YY": lambda dt: f"{dt.year:d}"[2:],
102+
"YYYY": lambda dt: f"{dt.year:04d}",
103+
"YY": lambda dt: f"{dt.year % 100:02d}",
104104
"Y": lambda dt: f"{dt.year:d}",
105105
# Quarter
106106
"Q": lambda dt: f"{dt.quarter:d}",
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from __future__ import annotations
2+
3+
import pytest
4+
5+
import pendulum
6+
7+
from pendulum.formatting import Formatter
8+
9+
10+
@pytest.mark.parametrize(
11+
"year, full, short",
12+
[
13+
(1, "0001", "01"),
14+
(9, "0009", "09"),
15+
(10, "0010", "10"),
16+
(99, "0099", "99"),
17+
(100, "0100", "00"),
18+
(101, "0101", "01"),
19+
(999, "0999", "99"),
20+
(1000, "1000", "00"),
21+
(2009, "2009", "09"),
22+
(9999, "9999", "99"),
23+
],
24+
)
25+
def test_year_tokens_have_fixed_width(year: int, full: str, short: str) -> None:
26+
value = pendulum.datetime(year, 3, 14)
27+
assert Formatter().format(value, "YYYY YY Y") == f"{full} {short} {year}"
28+
assert value.format("YYYY-MM-DD") == f"{full}-03-14"
29+
assert value.format("YY-MM-DD") == f"{short}-03-14"
30+
assert pendulum.from_format(value.format("YYYY-MM-DD"), "YYYY-MM-DD") == value
31+
32+
33+
def test_year_padding_applies_to_localized_long_formats() -> None:
34+
value = pendulum.datetime(42, 3, 14)
35+
assert value.format("L", locale="en") == "03/14/0042"
36+
assert value.format("[YYYY] YYYY [YY] YY [Y] Y") == "YYYY 0042 YY 42 Y 42"

0 commit comments

Comments
 (0)