原创 TypeError:Object of type Timestamp is not JSON serializable

原始需求:将 dataframe 转成 dict 后,在序列化为 JSON 字符串时,dict 中的 timestamp 字段类型的字段无法序列化,并提示 TypeError: Object of type Timestamp is not JSON serializable

代码如下:

[119]:  forecast['ds']
[119]: 
        0      2007-12-10
        1      2007-12-11
        2      2007-12-12
        3      2007-12-13
        4      2007-12-14
                ...    
        3265   2017-01-15
        3266   2017-01-16
        3267   2017-01-17
        3268   2017-01-18
        3269   2017-01-19
        Name: ds, Length: 3270, dtype: datetime64[ns]

[120]: predict_result_dict = forecast[['ds', 'yhat']].to_dict(orient="list")
       predict_result_dict      
[120]:
        {'ds': [Timestamp('2007-12-10 00:00:00'),
        Timestamp('2007-12-11 00:00:00'),
        Timestamp('2007-12-12 00:00:00'),
        Timestamp('2007-12-13 00:00:00'),
        Timestamp('2007-12-14 00:00:00'),
        Timestamp('2007-12-15 00:00:00'), 
        Timestamp('2007-12-16 00:00:00'),
        Timestamp('2007-12-17 00:00:00'),
        Timestamp('2007-12-18 00:00:00'),
        Timestamp('2007-12-19 00:00:00'),
        Timestamp('2007-12-20 00:00:00'),
        Timestamp('2007-12-21 00:00:00'),
        Timestamp('2007-12-22 00:00:00'),
        Timestamp('2007-12-23 00:00:00'),
        Timestamp('2007-12-24 00:00:00'), 
[121]: json.dumps(predict_result_dict)
       ...
       TypeError: Object of type Timestamp is not JSON serializable
       ....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

解决办法:使用 DataFrame.astype 将 ds 字段转成 str 类型,然后再转成 dict,之后在序列化为 JSON ,即正常。

代码如下:

[122]:
        forecast['ds'] = forecast['ds'].astype(str)
        predict_result_dict = forecast[['ds', 'yhat']].to_dict(orient="list")
        json.dumps(predict_result_dict)

[122]:
        '{"ds": ["2007-12-10", "2007-12-11", "2007-12-12", "2007-12-13", "2007-12-14"],"yhat": [8.845280013796097, 8.593816343132877, 8.389622567288246, 8.367536649208493, 8.355486755751214]}'
1
2
3
4
5
6
7

reference