防止 pandas to_json()将时间分量添加到日期对象 [英] Prevent Pandas to_json() from adding time component to date object

查看:94
本文介绍了防止 pandas to_json()将时间分量添加到日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含一些日期对象。我需要转换为用于JavaScript的json,这需要YYYY-MM-DD,但 to_json()会不断添加时间分量。我已经看到了许多首先转换为字符串的答案,但这是循环的大约15个查询的查询的一部分,每个查询具有许多列(针对SO问题对其进行了简化),我不想将每个列转换硬编码为

I have a dataframe of that contains some date objects. I need to convert to a json for use in JavaScript, which requires YYYY-MM-DD, but to_json() keeps adding a time component. I've seen a number of answers that convert to a string first, but this is part of a loop of about 15 queries each with many columns (simplified it for the SO question) and I don't want to hardcode each column conversion as there are a lot.

import pandas as pd
from datetime import date
df = pd.DataFrame(data=[[date(year=2018, month=1, day=1)]])    
print df.to_json(orient='records', date_format='iso', date_unit='s')

输出:

[{"0":"2018-01-01T00:00:00Z"}]

所需的输出:

[{"0":"2018-01-01"}]


推荐答案

熊猫当前不具有该功能。对此有一个未解决的问题,如果将来的版本中添加了 date_format 参数的更多选项,您应该订阅此问题(这似乎是一个合理的功能要求) :

Pandas does not currently have the feature. There is an open issue about this, you should subscribe to the issue in case more options for the date_format argument are added in a future release (which seems like a reasonable feature request):

没办法使用to_json只写过期的日期时间#16492

No way with to_json to write only date out of datetime #16492

在转储json之前将相关的列手动转换为字符串可能是最好的选择。

Manually converting the relevant columns to string before dumping out json is likely the best option.

这篇关于防止 pandas to_json()将时间分量添加到日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆