【发布时间】:2021-07-27 09:03:28
【问题描述】:
我正在尝试将 json 读入 Pandas 中的数据框,然后使用 pandas ExcelWriter 将 df 输出到 excel。我在excel中得到混合输出。 json 中的两种日期时间格式都是 YYYY-MM-DDTHH:MM:SS.sssZ。例如,2020-04-23T07:39:51.918Z。
这是我的代码:
import pandas as pd
from datetime import datetime
with open('simple_json_test.txt', 'r') as f:
data = f.readlines()
data = map(lambda x: x.rstrip(), data)
data_json_str = "[" + ','.join(data) + "]"
df = pd.read_json(data_json_str)
print (df.dtypes)
# Write the dataframe to excel
writer = pd.ExcelWriter('simpleJsonToExcelTest.xlsx', engine='xlsxwriter')
df.to_excel(writer, header=True, sheet_name='Pandas_Test',index=False)
writer.save()
运行代码时出现以下错误:“ValueError”Excel 不支持带时区的日期时间。在写入 Excel 之前,请确保日期时间是不知道时区的"
我输出 df.types() 来查看列是什么类型:
Triggered Time object
action_time datetime64[ns]
dtype: object
这很奇怪,因为两者在 json 中的格式似乎相同。这是json
{"action_time":"2020-04-23T07:39:51.918Z","Triggered Time":"2020-04-23T07:39:51.900Z"}
{"action_time":"2020-04-23T07:39:51.918Z","Triggered Time":"2020-04-23T07:39:51.900Z"}
{"action_time":"2020-04-23T07:39:51.918Z","Triggered Time":"2020-04-23T07:39:51.900Z"}
{"action_time":"2020-04-23T07:39:51.918Z","Triggered Time":"2020-04-23T07:39:51.900Z"}
我对代码进行了以下更新并使其成功运行,但是 excel 文件中的输出不一样。
import pandas as pd
from datetime import datetime
with open('simple_json_test.txt', 'r') as f:
data = f.readlines()
data = map(lambda x: x.rstrip(), data)
data_json_str = "[" + ','.join(data) + "]"
df = pd.read_json(data_json_str)
print (df.dtypes)
df['action_time'] = pd.to_datetime(df['action_time'],errors='coerce',utc=True)
df['action_time'] = df['action_time'].apply(lambda a: datetime.strftime(a, "%Y-%m-%d %H:%M:%S%f")[:-3])
df['action_time'] = pd.to_datetime(df['action_time'], errors='coerce',format='%Y-%m-%d %H:%M:%S%f')
print (df.dtypes)
# Write the dataframe to excel
writer = pd.ExcelWriter('simpleJsonToExcelTest.xlsx', engine='xlsxwriter')
df.to_excel(writer, header=True, sheet_name='Pandas_Test',index=False)
writer.save()
我是 pandas 的新手,所以我尝试过的一些事情,我并不完全理解并且可能不正确。 excel文件中的输出为:
action_time 列是 YYYY-MM-DD HH:MM:SS 触发时间为 YYYY-MM-DDTHH:MM:SS.sssZ
| action_time | Triggered Time |
|---|---|
| 2020-04-23 07:39:51 | 2020-04-23T07:39:51.918Z |
触发时间是我希望的格式 (YYYY-MM-DDTHH:MM:SS.sssZ)。我需要保留毫秒。看起来 excel 中的 action_time 是一个实际的日期字段,而触发时间不是。
我什至尝试将 action_time 的数据类型转换为对象,但没有成功。我被困在这一点上。
【问题讨论】:
标签: json python-3.x pandas pandas.excelwriter