Thanks. This is what I ended up with. Not quite done testing, but it seems to work. I'm happy to donate it to back to the project if people think it's of sufficiently general value. It uses total_seconds(), so won't work with Python 2.6 or earlier.
class TimedeltaField(BaseField):
"""A timedelta field.
Looks to the outside world like a datatime.timedelta, but stores
in the database as an integer (or float) number of seconds.
"""
def validate(self, value):
if not isinstance(value, (timedelta, int, float)):
self.error(u'cannot parse timedelta "%r"' % value)
def to_mongo(self, value):
return self.prepare_query_value(None, value)
def to_python(self, value):
return timedelta(seconds=value)
def prepare_query_value(self, op, value):
if value is None:
return value
if isinstance(value, timedelta):
return value.total_seconds()
if isinstance(value, (int, float)):
return value