Skip to content

fix: preserve instance locale in datetime.astimezone()#190

Open
patchwright wants to merge 1 commit into
slashmili:mainfrom
patchwright:fix/astimezone-keeps-locale
Open

fix: preserve instance locale in datetime.astimezone()#190
patchwright wants to merge 1 commit into
slashmili:mainfrom
patchwright:fix/astimezone-keeps-locale

Conversation

@patchwright

Copy link
Copy Markdown

Problem

jdatetime.datetime.astimezone(tz) silently drops the instance locale and resets it to the global default.

>>> import datetime, jdatetime
>>> jdatetime.set_locale('en_US')
>>> teh = datetime.timezone(datetime.timedelta(hours=3, minutes=30))
>>> dt = jdatetime.datetime(1397, 8, 17, 7, 54, 28, tzinfo=teh, locale='fa_IR')
>>> dt.astimezone(datetime.timezone.utc).locale
'en_US'

Expected 'fa_IR'. Confirmed on main HEAD 4b461d1.

Root cause

astimezone rebuilds the result with datetime.fromgregorian(datetime=gdt) and does not pass the instance locale (jdatetime/__init__.py:1176). Every sibling that round-trips through fromgregorian passes it: __add__ (1009), __sub__ (1022), replace (1002), combine (860). astimezone is the only outlier.

Fix

Pass locale=self.locale, matching the siblings. One line, no API change.

-        return datetime.fromgregorian(datetime=gdt)
+        return datetime.fromgregorian(datetime=gdt, locale=self.locale)

How to test

Added test_astimezone_keeps_locale, next to test_replace_keeps_date_locale. It fails on main with AssertionError: 'en_US' != 'fa_IR' and passes with this change. Real output:

before: astimezone().locale = 'en_US'
after:  astimezone().locale = 'fa_IR'

The full suite is green apart from a pre-existing test_with_fa_locale that fails with locale.Error: unsupported locale setting on machines missing the fa_IR.UTF-8 system locale. It fails identically on unpatched main, so it is unrelated to this change. A CHANGELOG entry is included.

Backward compatibility

No breaking changes. After astimezone, the instance locale is preserved, consistent with replace, combine, __add__, and __sub__.


Assisted-by: Claude (code generation, reviewed and tested locally)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant