JSON 使用 Pandas Excelwriter 在 excel 中输入日期时间格式不正确

JSON input Datetime not formatting correctly in excel using Pandas Excelwriter

我正在尝试将 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 的数据类型转换为对象,但没有成功。我卡在这一点上了。

我不知道为什么“action_time”和“触发时间”被解析为不同的类型,但替换“触发时间”中的 space 会将两者转换为 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 文档中的 Formatting of the Dataframe output