From 750abbc9dc097883833dd05b54f97ac595cf9f4e Mon Sep 17 00:00:00 2001 From: Huanyi Xie <74809554+xiehuanyi@users.noreply.github.com> Date: Mon, 12 Oct 2026 22:20:42 +0300 Subject: [PATCH] Use local timezone by default in DateTime.astimezone --- CHANGELOG.md | 2 ++ tests/test_items.py | 12 ++++++++++++ tomlkit/items.py | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0af52c54..03ec2f94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Fixed +- Allow `DateTime.astimezone()` to use the local timezone when no timezone argument is supplied, matching `datetime.datetime`. + - Fix valid TOML being rejected when an out-of-order table reopens an implicit super-table with a dotted key: `[a.b.c]` then `[a]` with `b.z = 1` extends the implicit `a.b` super-table rather than redefining it (stdlib `tomllib` accepts it), so it now parses and round-trips instead of raising `Redefinition of an existing table`. The concrete-table case (`[a.b]` then `[a]` `b.z = 1`) stays rejected. ([#565](https://github.com/python-poetry/tomlkit/pull/565)) - Fix appending a key to a parsed inline table that uses `", "` separators emitting a bare `","` for the new entry, leaving the table inconsistently spaced (e.g. `{x = 1, y = 2,z = 3}`). ([#595](https://github.com/python-poetry/tomlkit/pull/595)) diff --git a/tests/test_items.py b/tests/test_items.py index bbe1b2ed..e72f45ce 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -803,6 +803,18 @@ def test_datetimes_behave_like_datetimes(tz_utc: tzinfo, tz_pst: tzinfo) -> None assert doc.as_string() == "dt = 2018-07-23T12:34:56-05:00" +def test_datetime_astimezone_defaults_to_local_timezone() -> None: + value = parse("time = 1979-05-27T07:32:00Z # birthday\n")["time"] + expected = datetime(1979, 5, 27, 7, 32, tzinfo=timezone.utc).astimezone() + + result = value.astimezone() + + assert isinstance(result, DateTime) + assert result.unwrap() == expected + assert result.as_string() == expected.isoformat() + assert result == value.astimezone(None) + + @pytest.mark.parametrize("fold", [0, 1]) def test_datetime_subtraction_preserves_input_fold(tz_fold: tzinfo, fold: int) -> None: value = datetime(2018, 11, 4, 1, 30, tzinfo=tz_fold, fold=fold) diff --git a/tomlkit/items.py b/tomlkit/items.py index 26b01097..1d0477be 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1181,7 +1181,7 @@ def __sub__(self, other: timedelta | datetime) -> DateTime | timedelta: def replace(self, *args: object, **kwargs: object) -> DateTime: return self._new(super().replace(*args, **kwargs)) # type: ignore[arg-type] - def astimezone(self, tz: tzinfo) -> DateTime: # type: ignore[override] + def astimezone(self, tz: tzinfo | None = None) -> DateTime: result = super().astimezone(tz) if PY38: return result