简体   繁体   中英

pandas to_json changes date format to "epoch time"

whenever i convert dataFrame to_json any date format changes to " epoch time "

[{"idNo":1234567891012,"Name":"Jack","genderType":"male","Date":1544572800000,"branchName":"NY","location":"loc1","pCode":123}] Original date was Date:2018-12-12

my python code

@app.route("/fileviewer/" , methods=["GET" , "POST"])
def fileviewer(name):
dest = (file_destination)
df = pd.read_excel(dest)
print(df)
x1=df.to_json(orient ='records')
print(x1)
render_template('fileviewer.html',x=df.to_html())
return render_template('fileviewer.html',x=x1)

df prints fine

x1 prints with the "epoch time"

You can change the format using the option date_format :

>>> df = pandas.DataFrame([
    {'A' : 0, 't' : datetime.datetime(2018, 1, 2)},
    {'A' : 1, 't' : datetime.datetime(2018, 1, 5)},
    {'A' : 2, 't' : datetime.datetime(2018, 1, 7)}
])
>>> df.to_json(date_format = 'iso')
'{"A":{"0":0,"1":1,"2":2},"t":{"0":"2018-01-02T00:00:00.000Z","1":"2018-01-05T00:00:00.000Z","2":"2018-01-07T00:00:00.000Z"}}'

I found a great solution here

df.assign(
    **df.select_dtypes(['datetime']).astype(str).to_dict('list')
).to_json(orient="records")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM