我有以下代码:
>>> from datetime import datetime
>>> df = pd.DataFrame({"a" : [datetime(2017, 1, 3), datetime(2017, 2, 4)], "b" : [2, 4]})
>>> df
a b
0 2017-01-03 2
1 2017-02-04 4
>>> df.to_json(orient = "index", date_format = "iso")
'{"0":{"a":"2017-01-03T00:00:00.000Z","b":2},"1":{"a":"2017-02-04T00:00:00.000Z","b":4}}'
有没有办法将JSON中的日期时间字符串截断为"2017-01-03"
而不是"2017-01-03T00:00:00.000Z"
?
答案 0 :(得分:0)
您可以将它们转换为字符串,然后导出:
df.astype(str).to_json(orient = "index", date_format = "iso")
Out[45]: '{"0":{"a":"2017-01-03","b":"2"},"1":{"a":"2017-02-04","b":"4"}}'
答案 1 :(得分:0)
首先转换为适当的字符串:
df.a = df.a.dt.date.astype(str)
这会给'{"a":{"0":"2017-01-03","1":"2017-02-04"},"b":{"0":2,"1":4}}'
或者,您可以在json字符串上调用.replace('T00:00:00.000Z','')
。
答案 2 :(得分:0)
您可以使用strftime
或dt.date
与astype
一起使用assign
转换为string
:
print (df.assign(a=df['a'].dt.strftime('%Y-%m-%d')).to_json(orient = "index"))
{"0":{"a":"2017-01-03","b":2},"1":{"a":"2017-02-04","b":4}}
print (df.assign(a=df['a'].dt.date.astype(str)).to_json(orient = "index"))
{"0":{"a":"2017-01-03","b":2},"1":{"a":"2017-02-04","b":4}}
print (df.dtypes)
a datetime64[ns]
b int64
dtype: object
如果没有问题,请更改datetime列的原始dtype
:
df['a'] = df['a'].dt.strftime('%Y-%m-%d')
print (df.to_json(orient = "index"))
{"0":{"a":"2017-01-03","b":2},"1":{"a":"2017-02-04","b":4}}
print (df.dtypes)
a object
b int64
dtype: object