【问题标题】:JSON input Datetime not formatting correctly in excel using Pandas Excelwriter使用 Pandas Excelwriter 在 excel 中 JSON 输入日期时间格式不正确
【发布时间】: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


    【解决方案1】:

    我不知道为什么“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 文档中的 Formatting of the Dataframe output

    【讨论】:

    • 谢谢@jmcnamara。我仍然在“df.to_excel(writer ...)”行上遇到同样的错误。
    • 在这种情况下,您需要从日期时间对象中删除时区信息。类似:df['action_time'] = df['action_time'].dt.tz_localize(None)(两列)。
    • 实际上,我错误地注释了df[] 语句,因为它们不在您的代码示例中。
    • 如果您有一个新问题,您应该将其作为一个新问题发布,并附上一个示例,说明什么是有效的,什么是无效的。
    • 感谢您的帮助@jmcamara。真的很感激。
    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多