首页 > 解决方案 > 使用 Pandas Excelwriter 在 Excel 中未正确格式化 JSON 输入日期时间

问题描述

我正在尝试将 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()

我是熊猫新手,所以我尝试过的一些事情,我不完全理解并且可能不正确。excel文件中的输出是:

action_time列是 YYYY-MM-DD HH:MM:SS 触发时间是 YYYY-MM-DDTHH:MM:SS.sssZ

动作时间 触发时间
2020-04-23 07:39:51 2020-04-23T07:39:51.918Z

触发时间是我想要的格式(YYYY-MM-DDTHH:MM:SS.sssZ)。我需要保留毫秒。看起来 excel 中的 action_time 是一个实际的日期字段,而触发时间不是。

我什至尝试将 action_time 的数据类型转换为对象,但没有奏效。我被困在这一点上。

标签: jsonpython-3.xpandaspandas.excelwriter

解决方案


我不知道为什么“action_time”和“Triggered Time”被解析为不同的类型,但替换“Triggered Time”中的空格会将两者都转换为datetime64[ns]. 也许其他人可以解释那部分。

无论如何,有了它,您可以像这样在 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 = map(lambda x: x.replace('Triggered Time', 'Triggered_Time'), 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',
                        datetime_format='yyyy-mm-dd hh:mm:ss.000')

df.to_excel(writer, header=True, sheet_name='Pandas_Test', index=False)

# Widen the column for visibility.
worksheet = writer.sheets['Pandas_Test']
worksheet.set_column('A:B', 25)

writer.save()

如果需要,从日期中删除时区。我不必那样做。输出:

在此处输入图像描述

另请参阅XlsxWriter 文档中的 Dataframe 输出格式


推荐阅读