Is it possible to use a Postgres Interval data type with Marshmallow schema serialization?

Question:

SqlAlchemy supports Interval data types like this:

class Sample(Base):
    __tablename__ = "samples"
    id = Column(Integer(), primary_key=True)
    time_interval = Column(Interval(), nullable=True)

Is it possible to serialize an interval column type using Marshmallow schemas? I was hoping for something like the following:

class SampleSchema(Schema):
    id = fields.Int()
    time_interval = fields.Interval(allow_none=True)  # not supported

…but the interval data type is not supported by Marshmallow. The Marshmallow API documentation mentions other raw data types and strings, but so far I haven’t been able to get this to work.

TypeError: Object of type 'timedelta' is not JSON serializable

Thank you for any tips or suggestions.

Asked By: Ender2050

||

Answers:

Although it doesn’t provide any validation, I was able to get the schema to work using string:

class SampleSchema(Schema):
    id = fields.Int()
    time_interval = fields.String(allow_none=True)
Answered By: Ender2050

You can use TimeDelta class of Marshmallow Fields as stated in documentation.

You can serialize to datetime.timedelta and deseriliaze with Integer(default as seconds).

Answered By: Burak Özalp