35 lines
920 B
Python
35 lines
920 B
Python
import json
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
|
|
class DateTimeEncoder(json.JSONEncoder):
|
|
"""A custom JSON encoder that handles datetime objects.
|
|
|
|
This encoder extends the json.JSONEncoder class to provide serialization
|
|
support for datetime objects, converting them to ISO format strings.
|
|
|
|
Methods
|
|
-------
|
|
default(obj: Any) -> str
|
|
Encode datetime objects as ISO format strings.
|
|
"""
|
|
|
|
def default(self, obj: Any) -> str:
|
|
"""Encode the given object as a JSON-serializable type.
|
|
|
|
Parameters
|
|
----------
|
|
obj : Any
|
|
The object to encode.
|
|
|
|
Returns
|
|
-------
|
|
str
|
|
The ISO format string if the object is a datetime, otherwise
|
|
delegates to the superclass encoder.
|
|
"""
|
|
if isinstance(obj, datetime):
|
|
return obj.isoformat()
|
|
return super().default(obj)
|