Created
March 11, 2011 20:39
-
-
Save weaver/866528 to your computer and use it in GitHub Desktop.
Convert dates to strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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