如何在python中的json对象中反序列化日期时间?

时间:2013-02-21 06:14:34

标签: python json datetime

我原来的字典是

A = {                                                                                                  
    'date': datetime.date(2013, 1, 1),
    'price': 100
}

由于datetime.date不可序列化,我添加了一个默认函数来处理:

B = json.dumps(A, default=lambda obj:obj.isoformat() if hasattr(obj, 'isoformat') else obj)

我的问题是,当我使用'date'将其转换回原始字典时,如何对json.loads字段进行反序列化?

3 个答案:

答案 0 :(得分:9)

from datetime import datetime

def load_with_datetime(pairs, format='%Y-%m-%d'):
    """Load with dates"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = datetime.strptime(v, format).date()
            except ValueError:
                d[k] = v
        else:
            d[k] = v             
    return d

dump = json.dumps(A, default = f)
json.loads(dump, object_pairs_hook=load_with_datetime)

# {u'date': datetime.date(2013, 1, 1), u'price': 100}

答案 1 :(得分:2)

继续您的示例代码,

C = json.loads(B)
C['date'] = datetime.datetime.strptime(C['date'], '%Y-%m-%d')
print C
# {u'date': datetime.datetime(2013, 1, 1, 0, 0), u'price': 100}

答案 2 :(得分:1)

使用pickle模块

    import pickle
    fileop = open("timeformat.txt","wb")
    pickle.dump(A,fileop)
    fileop.close()
    print pickle.load(open("timeformat.txt","rb"))
    print A['Date']


    >>>{'date': datetime.date(2013, 1, 1), 'price': 100}
    >>>2013-01-01