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

如何使用pd.read_excel读取Excel并让日期按指定格式输出为JSON

问题:如何将Pandas导出JSON时的日期转换为指定字符串格式?

我有一份Excel文件中的数据,使用以下Python代码读取并转换为JSON:

df = pd.read_excel(xls_file_path)
# Convert DataFrame to JSON
json_data = df.to_json(orient='records')
print(json_data)

得到的JSON结果如下:

[{"Name":"Deepak Kalindi","Employee ID":101,"Joining Date":1704153600000,"Leaving Date":null,"Monthly Salary":12000,"Number of full days":27,"Number of half days":2.5,"Number of leaves":1.5,"OT (full Day)":3,"OT (half Day)":2}]

需要让Joining Date字段在JSON字符串中显示为"02-01-2024"格式,该怎么做?


解决方法

核心思路是先将DataFrame中的日期列转换为目标格式的字符串,再导出JSON,具体步骤如下:

  1. 读取Excel时解析日期列:确保Pandas将Joining Date识别为datetime类型(避免后续处理时间戳数值):
df = pd.read_excel(xls_file_path, parse_dates=['Joining Date'])
  1. 将日期格式化为指定字符串:利用dt.strftime方法将datetime对象转为DD-MM-YYYY格式的字符串:
df['Joining Date'] = df['Joining Date'].dt.strftime('%d-%m-%Y')
  1. 导出为JSON:此时执行导出操作,日期就会以目标字符串格式输出:
json_data = df.to_json(orient='records')
print(json_data)

执行后得到的JSON结果:

[{"Name":"Deepak Kalindi","Employee ID":101,"Joining Date":"02-01-2024","Leaving Date":null,"Monthly Salary":12000,"Number of full days":27,"Number of half days":2.5,"Number of leaves":1.5,"OT (full Day)":3,"OT (half Day)":2}]

如果Leaving Date也需要相同格式处理,重复步骤2即可,空值(null)会被自动保留,不会出现报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:40:03