How to JSON serialize hh:mm:ss in Python? How to query its type?
Question: I need to serialize a python object into JSON and am having a hard time
converting time-counters into JSON-play-nice form

Say I have something like this:

    
    
     01:20:24    # hh:mm:ss
    

which is a time counter I'm increasing, while my script is running.

When done, I need to convert to JSON.

I'm currently trying this:

    
    
    dthandler = lambda obj: obj.isoformat() if isinstance(obj, time) else None
    this_object["totaltime"] = json.dumps(this_object["totaltime"], default=dthandler)
    

but I get an error on `time` being not a valid `class, type, or tuple of
classes and types`

**Question:**  
How do I serialize this? And is there a list of possible 'default-types' to
query against (Python newbie... sorely missing Javascript typeof)

Thanks!


Answer: This is not a JSON problem; your `time` reference is not what you think it is.

Make sure you have a `datetime.time` object there, and not the `time` module,
for example:

    
    
    >>> import datetime
    >>> import time
    >>> ref = datetime.time(10, 20)
    >>> isinstance(ref, time)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
    >>> isinstance(ref, datetime.time)
    True
    

If you use the _correct_ type to test against, things work fine:

    
    
    >>> import json
    >>> dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.time) else None
    >>> json.dumps(ref, default=dthandler)
    '"10:20:00"'
    

Note that the documentation expects the handler to raise a `TypeError` instead
of returning `None`; that way unserializable objects are at least treated as
errors:

    
    
    def dthandler(o):
        try:
            return o.isoformat()
        except AttributeError:
            raise TypeError
    

would be more Pythonic and correct.

