22
33from collections .abc import Iterable , Iterator , Mapping
44from dataclasses import asdict , dataclass , field , fields , is_dataclass
5- from datetime import date
5+ from datetime import date , time , timedelta
66from enum import Enum
77from typing import Any , Literal
88from xml .etree import ElementTree
@@ -27,7 +27,7 @@ def format_as_xml(
2727 This is useful since LLMs often find it easier to read semi-structured data (e.g. examples) as XML,
2828 rather than JSON etc.
2929
30- Supports: `str`, `bytes`, `bytearray`, `bool`, `int`, `float`, `date`, `datetime`, `Enum`,
30+ Supports: `str`, `bytes`, `bytearray`, `bool`, `int`, `float`, `date`, `datetime`, `time`, `timedelta`, ` Enum`,
3131 `Mapping`, `Iterable`, `dataclass`, and `BaseModel`.
3232
3333 Args:
@@ -104,8 +104,10 @@ def _to_xml(self, value: Any, path: str, tag: str | None = None) -> ElementTree.
104104 element .text = value .decode (errors = 'ignore' )
105105 elif isinstance (value , bool | int | float | Enum ):
106106 element .text = str (value )
107- elif isinstance (value , date ):
107+ elif isinstance (value , date | time ):
108108 element .text = value .isoformat ()
109+ elif isinstance (value , timedelta ):
110+ element .text = str (value )
109111 elif isinstance (value , Mapping ):
110112 if tag is None and path in self ._element_names :
111113 element .tag = self ._element_names [path ]
@@ -165,7 +167,7 @@ def _parse_data_structures(
165167 path : str = '' ,
166168 ):
167169 """Parse data structures as dataclasses or Pydantic models to extract element names and attributes."""
168- if value is None or isinstance (value , (str | int | float | date | bytearray | bytes | bool )):
170+ if value is None or isinstance (value , (str | int | float | date | time | timedelta | bytearray | bytes | bool )):
169171 return
170172 elif isinstance (value , Mapping ):
171173 for k , v in value .items (): # pyright: ignore[reportUnknownVariableType]
0 commit comments