将 pandas 数据帧保存到 google 表格时,Timestamp 类型的对象不可 JSON 序列化

问题描述 投票:0回答:1

这里没有Python经验。

我有一个

pandas
DataFrame
,其中一列的类型为
datetime64[ns]
。当尝试使用
gspread
将数据保存到 Google 表格时,我收到“
Object of type Timestamp is not JSON serializable
”错误(下面代码片段中的最后一行)。据我了解,我可以将
datetime64[ns]
更改为
string
,理论上它应该可以正常工作,但是将日期/时间列保留为
datetime64[ns]
pandas
中的
DataFrame
有一些优点。有没有什么好的方法可以将数据转储到谷歌表格而不更改数据框中的数据类型?这是我的代码:

cred = "service_account.json"
url = "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/edit#gid=0"

course_tm = pd.DataFrame.from_records([s.to_dict() for s in ft_records])

sa = gspread.service_account(filename=cred)
spreadsheet = sa.open_by_url(url)
worksheet = spreadsheet.worksheet("Sheet1")
worksheet.update([course_tm.columns.values.tolist()] + course_tm.values.tolist())

提前谢谢您

python pandas dataframe google-sheets gspread
1个回答
0
投票

我相信您的目标如下。

  • 在您的数据框中,包含一列“datetime64[ns]”对象。
  • 您希望将数据框的值放入 Google 电子表格中,而不更改原始数据框的数据类型。

既然如此,下面的修改如何?

修改后的脚本:

在测试此脚本之前,请将“datetime64[ns]”的列名称设置为

col_name

cred = "service_account.json"
url = "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/edit#gid=0"

course_tm = pd.DataFrame.from_records([s.to_dict() for s in ft_records])

sa = gspread.service_account(filename=cred)
spreadsheet = sa.open_by_url(url)
worksheet = spreadsheet.worksheet("Sheet1")

# I modified the below script.
col_name = "### column name ###"  # Please set column name of "datetime64[ns]"
temp = course_tm.copy()
temp[col_name] = temp[col_name].dt.strftime("%Y-%m-%d %H:%M:%S")
worksheet.update([temp.columns.values.tolist()] + temp.values.tolist(), value_input_option='USER_ENTERED')
  • 运行此修改后的脚本时,数据框将被复制。并且,“datetime64[ns]”列被转换为字符串类型。然后,使用
    value_input_option='USER_ENTERED'
    将这些值放入电子表格中。这样,插入的日期字符串值将作为日期对象放置。您可以修改电子表格上的日期格式。
© www.soinside.com 2019 - 2024. All rights reserved.