You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何DataFrame转JSON后日期转为毫秒?Flask接口序列化疑问

解决DataFrame转JSON时日期格式被转为时间戳的问题

不需要手动构建JSON,通过Pandas的内置参数或简单的列转换就能保留原始日期格式,以下是两种可行方案:

方案一:指定to_json的日期格式参数

如果你的日期列已经是Pandas的datetime类型,可在调用to_json时添加date_format='iso'参数,输出ISO标准的日期字符串:

js = json.loads(df.to_json(orient="records", date_format='iso'))

注:该参数输出格式为2024-04-15T11:20:20Z,若需要严格匹配Mon, 15 Apr 2024 11:20:20 GMT这种RFC格式,建议使用方案二。

方案二:将日期列转为指定格式的字符串

先把DataFrame中的日期列转换为目标字符串格式,再转JSON,即可完全保留原始格式:

# 替换"date_column"为实际日期列名
df["date_column"] = df["date_column"].dt.strftime('%a, %d %b %Y %H:%M:%S GMT')
# 执行JSON转换
js = json.loads(df.to_json(orient="records"))

如果日期列原本不是datetime类型,需先转换为datetime再格式化:

df["date_column"] = pd.to_datetime(df["date_column"]).dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

修改后的完整路由代码

@app.route("/tipi", methods=["GET"])
def sqltipi():
    try:
        department = request.args.get("department")
        ogc_fid = request.args.get("ogc_fid")
        score = request.args.get("score")

        longitude = request.args.get("longitude")
        latitude = request.args.get("latitude")
        rayon = request.args.get("rayon")

        if longitude is not None and latitude is not None and rayon is not None:
            df= DBP.load_point_rayon_tipi(longitude,latitude,rayon)
        elif ogc_fid is not None:
            df = DBP.load_brigades_tipi(ogc_fid)
        else:
            df = DBP.load_tipi(department)

        if score is not None:
            df = df[df["score"] == int(score)]

        # 添加日期列格式化步骤,替换为实际日期列名
        if "date_column" in df.columns:
            df["date_column"] = pd.to_datetime(df["date_column"]).dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

        js = json.loads(df.to_json(orient="records"))
        return js
    except Exception as e:
        error_message = "An error occurred: " + str(e)
        return jsonify({"error": error_message}), 500

内容的提问来源于stack exchange,提问作者Charles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:02:45