Backtestspydanticrun-20261005-183002#13422

Issue #13422 Merged fix PR #13437 Run 5 Oct 2026 · run-20261005-183002 pydantic/pydantic

to_json: timedelta_mode and temporal_mode break documented behavior

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Patch B fixes the root cause. It adds a separate `timedelta_mode` field to `SerializationConfig` and stops folding the legacy `timedelta_mode` into the unified `temporal_mode`. With that change, `datetime`, `date` and `time` follow `temporal_mode` while `timedelta` follows `timedelta_mode`. When `temporal_mode` is set to `seconds` or `milliseconds` it still takes precedence for timedeltas, which keeps that feature working. The resolution is applied consistently in the `to_json`/`to_jsonable_python` argument path, in the `ser_json_*` config path, in the inferred (Any) serializer for value, serialize and json-key paths, and in `TimeDeltaSerializer`, which now shares a helper. Patch B also adds targeted tests that would fail before the change and pass after it: the issue's exact example, parametrized combinations of the two modes, dict keys, a config-based Any serializer, and a pydantic `BaseModel` with `ser_json_timedelta='float'`. The `.pyi` docs are updated to describe the override. Patch A changes only docstrings and `config.py` text, with no behavior change and no tests. Its new docs also do not describe the reported behavior accurately: they still present `timedelta_mode` as affecting only timedeltas, while in fact `timedelta_mode='float'` with `temporal_mode='iso8601'` still turns datetimes into floats. So Patch A neither fixes the bug nor correctly documents it, and the issue explicitly prefers independent timedelta control. Patch B is clearly better.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

7m 19s

Wall-clock time in the container

Full test suite

No new failures

12,267 passed · 501 skipped · 12,768 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

145vs 55 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

pydantic_core.to_json (and to_jsonable_python) documents timedelta_mode and temporal_mode as independent parameters governing disjoint type sets:

  • timedelta_mode: How to serialize timedelta objects, either 'iso8601' or 'float'.
  • temporal_mode: How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'.

(This is what both the API docs and the shipped _pydantic_core.pyi type stub say.)

Given that contract, to_json(..., timedelta_mode="float", temporal_mode="iso8601") should serialize datetime/date/time as ISO 8601 strings and timedelta as a float. Instead, datetime/date/time are also coerced to unix-timestamp floats, timedelta_mode="float" silently overrides temporal_mode="iso8601" for all temporal types.

There is no combination of the two parameters that yields ISO datetimes with float-second timedeltas, even though the documented parameters imply there should be.

Root cause / regression. This regressed in #1743. Before that PR, SerializationConfig had a dedicated timedelta_mode: TimedeltaMode field and to_json had no temporal_mode parameter, so timedelta_mode was genuinely independent. #1743 replaced the dedicated field with a single unified temporal_mode and retrofitted timedelta_mode as a legacy alias that maps into it.

Either the docs/.pyi should be corrected to state that timedelta_mode is a deprecated alias that affects all temporal types, or (preferably) timedelta should retain an independent setting so the documented behavior holds. Personally I have a requirement to be able to set the timedelta format independent of the other datetime types.

Example Code

import datetime
import pydantic_core

payload = {
    "dt": datetime.datetime(2026, 7, 9, 12, 0, 0),
    "d": datetime.date(2026, 7, 9),
    "t": datetime.time(12, 0, 0),
    "td": datetime.timedelta(hours=1, minutes=30),
}

# Per the docs: temporal_mode governs dt/d/t; timedelta_mode governs td.
actual = pydantic_core.to_json(
    payload, timedelta_mode="float", temporal_mode="iso8601"
).decode()

expected = '{"dt":"2026-07-09T12:00:00","d":"2026-07-09","t":"12:00:00","td":5400.0}'

print("actual  :", actual)
print("expected:", expected)
assert actual == expected, "timedelta_mode='float' wrongly coerced datetime/date/time to floats"
# AssertionError: actual == {"dt":1783598400.0,"d":1783555200.0,"t":43200.0,"td":5400.0}

Python, Pydantic & OS Version

pydantic version: 2.13.4
        pydantic-core version: 2.46.4
          pydantic-core build: profile=release pgo=false
               python version: 3.11.14 (main, Oct 10 2025, 12:48:11) [Clang 20.1.4 ]
                     platform: Linux-6.17.0-35-generic-x86_64-with-glibc2.39
             related packages: typing_extensions-4.16.0 mypy-2.2.0 email-validator-2.3.0 pydantic-settings-2.14.2 pydantic-extra-types-2.11.1
                       commit: unknown

The two patches

Our patch+120 −25
pydantic-core/python/pydantic_core/_pydantic_core.pyiindex c13dd4d2..96884e05 100644@@ -452,6 +452,7 @@ def to_json(         timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.         temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.             `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+            If set to `'seconds'` or `'milliseconds'`, this also applies to `timedelta` objects, overriding `timedelta_mode`.          bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.@@ -537,6 +538,7 @@ def to_jsonable_python(         timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.         temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.             `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+            If set to `'seconds'` or `'milliseconds'`, this also applies to `timedelta` objects, overriding `timedelta_mode`.          bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.pydantic-core/src/serializers/config.rsindex 9a1377c6..a4fabb10 100644@@ -21,7 +21,10 @@ use super::errors::py_err_se_err; #[derive(Debug, Clone, Copy)] #[allow(clippy::struct_field_names)] pub(crate) struct SerializationConfig {+    /// Mode used for `datetime`, `date` and `time` values.     pub temporal_mode: TemporalMode,+    /// Mode used for `timedelta` values, resolved from the temporal mode and the legacy timedelta mode.+    pub timedelta_mode: TemporalMode,     pub bytes_mode: BytesMode,     pub inf_nan_mode: InfNanMode, }@@ -30,6 +33,7 @@ impl Default for SerializationConfig {     fn default() -> Self {         Self {             temporal_mode: TemporalMode::default(),+            timedelta_mode: TemporalMode::default(),             bytes_mode: BytesMode::default(),             inf_nan_mode: InfNanMode::Constants,         }@@ -38,18 +42,13 @@ impl Default for SerializationConfig {  impl SerializationConfig {     pub fn from_config(config: Option<&Bound<'_, PyDict>>) -> PyResult<Self> {-        let temporal_set = config-            .and_then(|cfg| cfg.contains(intern!(cfg.py(), "ser_json_temporal")).ok())-            .unwrap_or(false);-        let temporal_mode = if temporal_set {-            TemporalMode::from_config(config)?-        } else {-            TimedeltaMode::from_config(config)?.into()-        };+        let temporal_mode = TemporalMode::from_config(config)?;+        let timedelta_mode = TemporalMode::timedelta_from_config(config)?;         let bytes_mode = BytesMode::from_config(config)?;         let inf_nan_mode = InfNanMode::from_config(config)?;         Ok(Self {             temporal_mode,+            timedelta_mode,             bytes_mode,             inf_nan_mode,         })@@ -61,13 +60,18 @@ impl SerializationConfig {         bytes_mode: &str,         inf_nan_mode: &str,     ) -> PyResult<Self> {-        let resolved_temporal_mode = if temporal_mode != "iso8601" {-            TemporalMode::from_str(temporal_mode)?+        // `timedelta_mode` only applies to `timedelta` values; `temporal_mode` applies to+        // `datetime`, `date` and `time`, and also to `timedelta` when set to a non-default value.+        let resolved_temporal_mode = TemporalMode::from_str(temporal_mode)?;+        let legacy_timedelta_mode = TimedeltaMode::from_str(timedelta_mode)?;+        let resolved_timedelta_mode = if resolved_temporal_mode == TemporalMode::Iso8601 {+            legacy_timedelta_mode.into()         } else {-            TimedeltaMode::from_str(timedelta_mode)?.into()+            resolved_temporal_mode         };         Ok(Self {             temporal_mode: resolved_temporal_mode,+            timedelta_mode: resolved_timedelta_mode,             bytes_mode: BytesMode::from_str(bytes_mode)?,             inf_nan_mode: InfNanMode::from_str(inf_nan_mode)?,         })@@ -158,6 +162,20 @@ impl From<TimedeltaMode> for TemporalMode { }  impl TemporalMode {+    /// Resolve the mode to use for `timedelta` values from a core config: `ser_json_temporal`+    /// takes precedence when set, otherwise the legacy `ser_json_timedelta` is used.+    pub fn timedelta_from_config(config: Option<&Bound<'_, PyDict>>) -> PyResult<Self> {+        let temporal_set = match config {+            Some(cfg) => cfg.contains(intern!(cfg.py(), "ser_json_temporal"))?,+            None => false,+        };+        if temporal_set {+            Self::from_config(config)+        } else {+            Ok(TimedeltaMode::from_config(config)?.into())+        }+    }+     pub fn datetime_to_json(self, py: Python, datetime: &Bound<'_, PyDateTime>) -> PyResult<Py<PyAny>> {         let dt = pydatetime_as_datetime(datetime)?;         match self {pydantic-core/src/serializers/infer.rsindex 141a4d5f..f8aaccf9 100644@@ -164,7 +164,7 @@ pub(crate) fn infer_to_python_known<'py>(             }             ObType::Timedelta => {                 let either_delta = EitherTimedelta::try_from(value)?;-                state.config.temporal_mode.timedelta_to_json(value.py(), either_delta)?+                state.config.timedelta_mode.timedelta_to_json(value.py(), either_delta)?             }             ObType::Url             | ObType::MultiHostUrl@@ -412,7 +412,7 @@ pub(crate) fn infer_serialize_known<'py, S: Serializer>(         }         ObType::Timedelta => {             let either_delta = EitherTimedelta::try_from(value).map_err(py_err_se_err)?;-            state.config.temporal_mode.timedelta_serialize(either_delta, serializer)+            state.config.timedelta_mode.timedelta_serialize(either_delta, serializer)         }         ObType::Url         | ObType::MultiHostUrl@@ -538,7 +538,7 @@ pub(crate) fn infer_json_key_known<'a, 'py>(         }         ObType::Timedelta => {             let either_delta = EitherTimedelta::try_from(key)?;-            state.config.temporal_mode.timedelta_json_key(&either_delta)+            state.config.timedelta_mode.timedelta_json_key(&either_delta)         }         ObType::Url         | ObType::MultiHostUrlpydantic-core/src/serializers/type_serializers/timedelta.rsindex b866bf2e..2a142ed2 100644@@ -1,4 +1,3 @@-use pyo3::intern; use pyo3::prelude::*; use pyo3::types::PyDict; use std::borrow::Cow;@@ -7,7 +6,7 @@ use std::sync::Arc; use crate::definitions::DefinitionsBuilder; use crate::input::EitherTimedelta; use crate::serializers::SerializationState;-use crate::serializers::config::{FromConfig, TemporalMode, TimedeltaMode};+use crate::serializers::config::TemporalMode;  use super::{     BuildSerializer, CombinedSerializer, SerMode, TypeSerializer, infer_json_key, infer_serialize, infer_to_python,@@ -26,15 +25,7 @@ impl BuildSerializer for TimeDeltaSerializer {         config: Option<&Bound<'_, PyDict>>,         _definitions: &mut DefinitionsBuilder<Arc<CombinedSerializer>>,     ) -> PyResult<Arc<CombinedSerializer>> {-        let temporal_set = config-            .and_then(|cfg| cfg.contains(intern!(cfg.py(), "ser_json_temporal")).ok())-            .unwrap_or(false);-        let temporal_mode = if temporal_set {-            TemporalMode::from_config(config)?-        } else {-            let td_mode = TimedeltaMode::from_config(config)?;-            td_mode.into()-        };+        let temporal_mode = TemporalMode::timedelta_from_config(config)?;          Ok(Arc::new(Self { temporal_mode }.into()))     }pydantic-core/tests/serializers/test_any.pyindex 3d2ca39f..cd9c3d7f 100644@@ -22,6 +22,7 @@ from pydantic_core import (     SchemaValidator,     core_schema,     to_json,+    to_jsonable_python, )  from ..conftest import plain_repr@@ -197,6 +198,24 @@ def test_any_config_timedelta_float():     assert s.to_json({h2: 'foo'}) == b'{"7200":"foo"}'  +def test_any_config_timedelta_float_does_not_affect_datetime_etc():+    s = SchemaSerializer(core_schema.any_schema(), config={'ser_json_timedelta': 'float'})+    payload = {+        'dt': datetime(2026, 7, 9, 12, 0, 0),+        'd': date(2026, 7, 9),+        't': time(12, 0, 0),+        'td': timedelta(hours=1, minutes=30),+    }+    expected = {'dt': '2026-07-09T12:00:00', 'd': '2026-07-09', 't': '12:00:00', 'td': 5400.0}+    assert s.to_python(payload, mode='json') == expected+    assert json.loads(s.to_json(payload)) == expected++    keys = {datetime(2026, 7, 9, 12, 0, 0): 1, date(2026, 7, 9): 2, time(12, 0, 0): 3, timedelta(seconds=90): 4}+    expected_keys = {'2026-07-09T12:00:00': 1, '2026-07-09': 2, '12:00:00': 3, '90': 4}+    assert s.to_python(keys, mode='json') == expected_keys+    assert json.loads(s.to_json(keys)) == expected_keys++ def test_any_config_timedelta_float_faction():     s = SchemaSerializer(core_schema.any_schema(), config={'ser_json_timedelta': 'float'})     one_half_s = timedelta(seconds=1.5)@@ -773,3 +792,49 @@ def test_ipaddress_type_inference(any_serializer, value, expected_json):     assert any_serializer.to_python(value) == value     assert any_serializer.to_python(value, mode='json') == expected_json     assert any_serializer.to_json(value) == f'"{expected_json}"'.encode()+++TEMPORAL_PAYLOAD = {+    'dt': datetime(2026, 7, 9, 12, 0, 0),+    'd': date(2026, 7, 9),+    't': time(12, 0, 0),+    'td': timedelta(hours=1, minutes=30),+}+++@pytest.mark.parametrize(+    'kwargs,expected',+    [+        (+            dict(timedelta_mode='float', temporal_mode='iso8601'),+            {'dt': '2026-07-09T12:00:00', 'd': '2026-07-09', 't': '12:00:00', 'td': 5400.0},+        ),+        (+            dict(timedelta_mode='float'),+            {'dt': '2026-07-09T12:00:00', 'd': '2026-07-09', 't': '12:00:00', 'td': 5400.0},+        ),+        (+            dict(timedelta_mode='iso8601', temporal_mode='seconds'),+            {'dt': 1783598400.0, 'd': 1783555200.0, 't': 43200.0, 'td': 5400.0},+        ),+        (+            dict(timedelta_mode='float', temporal_mode='milliseconds'),+            {'dt': 1783598400000.0, 'd': 1783555200000.0, 't': 43200000.0, 'td': 5400000.0},+        ),+    ],+)+def test_timedelta_mode_independent_of_temporal_mode(kwargs, expected):+    assert json.loads(to_json(TEMPORAL_PAYLOAD, **kwargs)) == expected+    assert to_jsonable_python(TEMPORAL_PAYLOAD, **kwargs) == expected+++def test_timedelta_mode_float_issue_example():+    actual = to_json(TEMPORAL_PAYLOAD, timedelta_mode='float', temporal_mode='iso8601')+    assert actual == b'{"dt":"2026-07-09T12:00:00","d":"2026-07-09","t":"12:00:00","td":5400.0}'+++def test_timedelta_mode_float_does_not_affect_datetime_keys():+    keys = {datetime(2026, 7, 9, 12, 0, 0): 1, date(2026, 7, 9): 2, time(12, 0, 0): 3, timedelta(seconds=90): 4}+    expected = {'2026-07-09T12:00:00': 1, '2026-07-09': 2, '12:00:00': 3, '90': 4}+    assert json.loads(to_json(keys, timedelta_mode='float')) == expected+    assert to_jsonable_python(keys, timedelta_mode='float') == expectedtests/test_json.pyindex ef5c98fa..6f362ab1 100644@@ -188,6 +188,25 @@ def test_subclass_custom_encoding():     assert m.model_dump_json() == '{"a":"Thu, 01 Jan 20 01:01:00","b":360000.0}'  +def test_ser_json_timedelta_float_does_not_affect_datetime_in_any():+    class Model(BaseModel):+        model_config = ConfigDict(ser_json_timedelta='float')++        data: Any++    m = Model(+        data={+            'dt': datetime(2026, 7, 9, 12, 0, 0),+            'd': date(2026, 7, 9),+            't': time(12, 0, 0),+            'td': timedelta(hours=1, minutes=30),+        }+    )+    expected = {'data': {'dt': '2026-07-09T12:00:00', 'd': '2026-07-09', 't': '12:00:00', 'td': 5400.0}}+    assert m.model_dump(mode='json') == expected+    assert json.loads(m.model_dump_json()) == expected++ def test_invalid_model():     class Foo:         pass 
Merged fix · PR #13437+49 −6
pydantic-core/python/pydantic_core/_pydantic_core.pyiindex c13dd4d21..12b8e4d49 100644@@ -449,10 +449,31 @@ def to_json(         by_alias: Whether to use the alias names of fields.         exclude_none: Whether to exclude fields that have a value of `None`.         round_trip: Whether to enable serialization and validation round-trip support.-        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.-        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.-            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+        timedelta_mode: The format of serialized timedeltas. Accepts the string values of `'iso8601'` and `'float'`. +            - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'float'` will serialize timedeltas to the total number of seconds.++            /// version-changed | v2.12+            It is now recommended to use the `temporal_mode` argument. `timedelta_mode` will be deprecated in v3.+            ///+        temporal_mode: The format of serialized temporal types from the [`datetime`][] module. This includes:++            - [`datetime.datetime`][]+            - [`datetime.date`][]+            - [`datetime.time`][]+            - [`datetime.timedelta`][]++            Can be one of:++            - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.+            - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch.++            /// version-added | v2.12+            This argument replaces `timedelta_mode`, which will be deprecated in v3. `temporal_mode` adds more+            configurability for the other temporal types. It takes precedence over `timedelta_mode`.+            ///         bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.         serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails@@ -534,10 +555,31 @@ def to_jsonable_python(         by_alias: Whether to use the alias names of fields.         exclude_none: Whether to exclude fields that have a value of `None`.         round_trip: Whether to enable serialization and validation round-trip support.-        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.-        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.-            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+        timedelta_mode: The format of serialized timedeltas. Accepts the string values of `'iso8601'` and `'float'`.++            - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'float'` will serialize timedeltas to the total number of seconds.++            /// version-changed | v2.12+            It is now recommended to use the `temporal_mode` argument. `timedelta_mode` will be deprecated in v3.+            ///+        temporal_mode: The format of serialized temporal types from the [`datetime`][] module. This includes:++            - [`datetime.datetime`][]+            - [`datetime.date`][]+            - [`datetime.time`][]+            - [`datetime.timedelta`][]++            Can be one of:++            - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.+            - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch. +            /// version-added | v2.12+            This argument replaces `timedelta_mode`, which will be deprecated in v3. `temporal_mode` adds more+            configurability for the other temporal types. It takes precedence over `timedelta_mode`.+            ///         bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.         serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that failspydantic/config.pyindex 5211aae83..e61029bdf 100644@@ -595,6 +595,7 @@ class ConfigDict(TypedDict, total=False):     /// version-added | v2.12     This setting replaces [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta],     which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types.+    It takes precedence over `ser_json_timedelta`.     ///     """