日期对象的json序列化


In [1]: import datetime

In [2]: d=datetime.datetime.now()                      #是一个对象

In [3]: d
Out[3]: datetime.datetime(2018, 8, 8, 18, 37, 48, 242295)

In [4]: print d
2018-08-08 18:37:48.242295

In [7]: type(d)

Out[7]: datetime.datetime

In [12]: d=datetime.datetime.now().strftime("%Y-%m-%d")     #变成字符串

In [13]: d
Out[13]: '2018-08-08'

In [14]: print d
2018-08-08

In [15]: type(d)
Out[15]: str

In [16]: import json

In [17]: json.dumps(d)                #可以使用json序列化
Out[17]: '"2018-08-08"'

In [18]: json.dumps(datetime.datetime.now())             #不可以使用json序列化
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-5898596fa331> in <module>()
----> 1 json.dumps(datetime.datetime.now()

TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'

In [20]: json.dumps(datetime.datetime.now().strftime("%Y-%m-%d"))
Out[20]: '"2018-08-08"'

猜你喜欢

转载自www.cnblogs.com/hyhyhy/p/9445070.html