这里没有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())
提前谢谢您
我相信您的目标如下。
既然如此,下面的修改如何?
在测试此脚本之前,请将“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')
value_input_option='USER_ENTERED'
将这些值放入电子表格中。这样,插入的日期字符串值将作为日期对象放置。您可以修改电子表格上的日期格式。