如何在pandas to_json datetime中截断日期字符串

时间:2017-05-24 00:04:53

标签: python pandas datetime

我有以下代码:

>>> 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"

3 个答案:

答案 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)

您可以使用strftimedt.dateastype一起使用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