【问题标题】:pandas to_json changes date format to "epoch time"pandas to_json 将日期格式更改为“纪元时间”
【发布时间】:2020-09-07 19:11:05
【问题描述】:

每当我将 dataFrame 转换为_json 时,任何日期格式都会更改为“纪元时间

[{"idNo":1234567891012,"Name":"Jack","genderType":"male","Date":1544572800000,"branchName":"NY","location":"loc1","pCode":123}] 原始日期是 Date:2018-12-12

我的python代码

@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 打印正常

x1 打印“纪元时间”

【问题讨论】:

    标签: python pandas flask


    【解决方案1】:

    您可以使用选项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"}}'
    

    【讨论】:

    • 所以在我的情况下 df.to_json(orient ='records',date_format = 'iso')?
    • 它有效,但它增加了时间:S,我不需要在这里添加时间戳。2018-12-12T00:00:00.000Z
    • 是否有可能只得到一个没有时间戳的普通日期?
    • @SujayDSa 你是什么意思?
    • @caverac 在执行 to_json 时会将 2018-01-05 转换为 2018-01-05T00:00:00.000Z。所以我不得不将我的日期单独转换为字符串,然后执行 to_json
    【解决方案2】:

    我找到了一个很好的解决方案here

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

    【讨论】:

      猜你喜欢
      • 2015-01-23
      • 1970-01-01
      • 2019-10-27
      • 2019-11-14
      • 2018-05-16
      • 2019-10-31
      • 1970-01-01
      • 2016-11-02
      • 2018-09-21
      相关资源
      最近更新 更多