我的数据框中有一个日期,格式如下
"2018-05-01"
"2018-05-02"
"2018-05-03"
我想在我的JSON
中将日期转换为类似的内容"2018-05-01T00:00:00.000Z"
"2018-05-02T00:00:00.000Z"
我曾尝试使用pd.to_datetime(df['date'])
但结果在我的JSON文件中变成1523404800000
。如何在我的JSON中获得"2018-05-02T00:00:00.000Z"
这样的格式?
答案 0 :(得分:1)
您正在df.to_json()
date_format='iso'
完整示例:
import pandas as pd
csvdata = '''\
date
2018-05-01
2018-05-02
2018-05-03'''
fileobj = pd.compat.StringIO(csvdata)
df = pd.read_csv(fileobj, sep='\s+')
# without conversion
print(df.to_json())
# with conversion
df['date'] = pd.to_datetime(df['date'])
print(df.to_json())
# with conversion and adding date_format = iso
print(df.to_json(date_format='iso'))
打印:
{"date":{"0":"2018-05-01","1":"2018-05-02","2":"2018-05-03"}}
{"date":{"0":1525132800000,"1":1525219200000,"2":1525305600000}}
{"date":{"0":"2018-05-01T00:00:00.000Z","1":"2018-05-02T00:00:00.000Z","2":"2018-05-03T00:00:00.000Z"}}