def default(self, o): if isinstance(o, datetime.datetime): r = o.isoformat() if o.microsecond: r = r[:23] + r[26:] if r.endswith("+00:00"): r = r[:-6] + "Z" return r elif isinstance(o, datetime.date): return o.isoformat() elif isinstance(o, datetime.time): if timezone.is_aware(o): raise ValueError("JSON can't represent timezone-aware times.") r = o.isoformat() if o.microsecond: r = r[:12] return r elif isinstance(o, datetime.timedelta): return duration.iso_string(o) elif isinstance(o, (decimal.Decimal, uuid.UUID)): return str(o) elif isinstance(o, enum.Enum): return o.value return super().default(o)
def test_iso_simple(): td = timedelta(hours=1, minutes=3, seconds=5) assert duration.iso_string(td) == "P0DT01H03M05S"
def test_iso_microseconds(): td = timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) assert duration.iso_string(td) == "P0DT01H03M05.012345S"
def test_iso_negative(): td = -1 * timedelta(days=1, hours=1, minutes=3, seconds=5) assert duration.iso_string(td) == "-P1DT01H03M05S"
def test_iso_days(): td = timedelta(days=1, hours=1, minutes=3, seconds=5) assert duration.iso_string(td) == "P1DT01H03M05S"