Skip to content

Instantly share code, notes, and snippets.

@weaver
Created March 11, 2011 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaver/866528 to your computer and use it in GitHub Desktop.
Save weaver/866528 to your computer and use it in GitHub Desktop.
Convert dates to strings
import json
from datetime import datetime
class Foo(object):
def __init__(self, when):
self.when = when
def __json__(self):
return self.__dict__
def dumps(obj):
return json.dumps(obj, default=convert)
def convert(obj):
if callable(getattr(obj, '__json__', None)):
return obj.__json__()
if isinstance(obj, datetime):
return str(obj)
raise TypeError("Cannot convert", obj)
print dumps(Foo(datetime.now()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment