Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion jupyter_client/jsonutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import warnings
from binascii import b2a_base64
from collections.abc import Iterable
from datetime import date, datetime
from datetime import date, datetime, timedelta
from typing import Any, Union

from dateutil.parser import isoparse as _dateutil_parse
Expand Down Expand Up @@ -126,6 +126,9 @@ def json_default(obj: Any) -> Any:
if isinstance(obj, numbers.Real):
return float(obj)

if isinstance(obj, timedelta):
return str(obj)

raise TypeError("%r is not JSON serializable" % obj)


Expand Down Expand Up @@ -192,5 +195,8 @@ def json_clean(obj: Any) -> Any:
if isinstance(obj, datetime | date):
return obj.strftime(ISO8601)

if isinstance(obj, timedelta):
return str(obj)

# we don't understand it, it's probably an unserializable object
raise ValueError("Can't clean for JSON: %r" % obj)
1 change: 1 addition & 0 deletions tests/test_jsonutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def test_json_default():
(MyFloat(), 3.14),
(MyInt(), 389),
(datetime.date(2025, 4, 8), "2025-04-08"),
(datetime.timedelta(days=2, minutes=1, seconds=10), "2 days, 0:01:10"),
]

for val, jval in pairs:
Expand Down