|
2 | 2 | Test output formatting for Series/DataFrame, including to_string & reprs
|
3 | 3 | """
|
4 | 4 |
|
5 |
| -from datetime import datetime |
| 5 | +from datetime import ( |
| 6 | + datetime, |
| 7 | + time, |
| 8 | +) |
6 | 9 | from io import StringIO
|
7 | 10 | import itertools
|
| 11 | +import locale |
8 | 12 | from operator import methodcaller
|
9 | 13 | import os
|
10 | 14 | from pathlib import Path
|
|
47 | 51 | use_32bit_repr = is_platform_windows() or not IS64
|
48 | 52 |
|
49 | 53 |
|
| 54 | +def get_local_am_pm(): |
| 55 | + """Return the AM and PM strings returned by strftime in current locale.""" |
| 56 | + am_local = time(1).strftime("%p") |
| 57 | + pm_local = time(13).strftime("%p") |
| 58 | + return am_local, pm_local |
| 59 | + |
| 60 | + |
50 | 61 | @pytest.fixture(params=["string", "pathlike", "buffer"])
|
51 | 62 | def filepath_or_buffer_id(request):
|
52 | 63 | """
|
@@ -3167,6 +3178,41 @@ def test_str(self):
|
3167 | 3178 | assert str(NaT) == "NaT"
|
3168 | 3179 |
|
3169 | 3180 |
|
| 3181 | +class TestPeriodIndexFormat: |
| 3182 | + def test_period_custom_locale(self, overridden_locale): |
| 3183 | + # GH#46319 locale-specific formatting directive leads to non-utf8 str result |
| 3184 | + |
| 3185 | + # Get locale-specific reference |
| 3186 | + am_local, pm_local = get_local_am_pm() |
| 3187 | + |
| 3188 | + # Scalar |
| 3189 | + per = pd.Period("2018-03-11 13:00", freq="H") |
| 3190 | + assert per.strftime("%p") == pm_local |
| 3191 | + |
| 3192 | + # Index |
| 3193 | + per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h") |
| 3194 | + formatted = per.format(date_format="%y %I:%M:%S%p") |
| 3195 | + assert formatted[0] == f"03 01:00:00{am_local}" |
| 3196 | + assert formatted[1] == f"03 01:00:00{pm_local}" |
| 3197 | + |
| 3198 | + |
| 3199 | +@pytest.fixture(params=[None, "fr_FR", "zh_CN"]) |
| 3200 | +def overridden_locale(request): |
| 3201 | + """A fixture used to temporarily change the locale""" |
| 3202 | + old = locale.setlocale(locale.LC_ALL) |
| 3203 | + target = request.param |
| 3204 | + if target is None: |
| 3205 | + yield old |
| 3206 | + else: |
| 3207 | + try: |
| 3208 | + locale.setlocale(locale.LC_ALL, target) |
| 3209 | + except locale.Error as e: |
| 3210 | + pytest.skip(f"Skipping as locale cannot be set. {type(e).__name__}: {e}") |
| 3211 | + else: |
| 3212 | + yield target |
| 3213 | + locale.setlocale(locale.LC_ALL, old) |
| 3214 | + |
| 3215 | + |
3170 | 3216 | class TestDatetimeIndexFormat:
|
3171 | 3217 | def test_datetime(self):
|
3172 | 3218 | formatted = pd.to_datetime([datetime(2003, 1, 1, 12), NaT]).format()
|
|
0 commit comments