如何修复 Python at Object of type datetime is not JSON serializable 错误

How to fix Python at Object of type datetime is not JSON serializable error

我通过 Twitter 使用数据挖掘。 所以我从 twitter 获取值 create_at 保存在文件 excel 之后发送文件 excel 到 google sheet 但是 发不出去
它有这个错误:

response = service.spreadsheets().values().append(
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\discovery.py", line 830, in method
headers, params, query, body = model.request(
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\model.py", line 161, in request
body_value = self.serialize(body_value)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\model.py", line 274, in serialize
return json.dumps(body_value)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 231, 
in dumps
return _default_encoder.encode(obj)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in 
encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in 
iterencode
return _iterencode(o, 0)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in 
default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

或者这段代码可能有问题?

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(r"F:\work\feen\WU\twitter.xlsx")
ws = wb.WorkSheets('Sheet1')
rngData = ws.Range('A1').CurrentRegion()

gsheet_id = 'sheet_id'
CLIENT_SECRET_FILE = 'credentials2.json'
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

service = Create_Service(CLIENT_SECRET_FILE,API_SERVICE_NAME,API_VERSION,SCOPES)
response = service.spreadsheets().values().append(
  spreadsheetId=gsheet_id,
  valueInputOption='RAW',
  range='data1!A1',
   body=dict(
      majorDimension='ROWS',
      values=rngData
  )
).execute()

wb.Close(r"F:\work\feen\WU\twitter.xlsx")

答案:

为了修复 Object of type datetime is not JSON serializable 错误,您需要将对象中 datetime 对象的所有实例转换为 string.

您的代码中还有其他错误,但是,这意味着仅此一项不会使您的程序 运行.

datetime 个对象转换为 string 个对象:

在 python 中,您可以使用 json.dumps() 将 JSON 数据本地转换为字符串,默认转换为字符串。

您可以通过在 service.spreadsheets().values().append() 调用之前添加此行来执行此操作:

//rngData at this point has already been assigned
rngData = json.dumps(rngData, indent = 4, sort_keys = True, default = str)

注意:这本身并不能修复您的代码!

其他事项:

调用 Google 工作表 API 时,以服务器期望接收这些请求的方式发出请求非常重要。也就是说,请务必按照文档进行请求

我在 linux 机器上,所以我无法测试 win32.Dispatch().Workbooks.Open().Worksheets().Range().CurrentRegion() 的输出格式,但是如果 Worksheet.Range property of Excel is anything to go by, I can safely assume that it's output isn't in the format required by the spreadsheets.values.append method 上的 Microsoft 文档:

array (ListValue format):

The data that was read or to be written. This is an array of arrays, the outer array representing all the data and each inner array representing a major dimension. Each item in the inner array corresponds with one cell.

For output, empty trailing rows and columns will not be included.

For input, supported value types are: bool, string, and double. Null values will be skipped. To set a cell to an empty value, set the string value to an empty string.

我不是 100% 确定输出是否相同,但为了尝试模拟您正在尝试的操作,我使用了 python 包 xlrd 从 Excel 你提供的文件是这样的:

workbook = xlrd.open_workbook("twitter.xlsx")
sheet = workbook.sheet_by_index(0)
data = [sheet.row_values(rowx) for rowx in range(sheet.nrows)]

并且,正如您在评论中提供的屏幕截图(见下文):

我也有同样的反应。向上滚动,错误是由于错误的请求:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/XXXXX/values/Sheet1%21A1:append?alt=json&valueInputOption=RAW returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue)..."

具体来说,Invalid value at 'data.values'。您需要遵守 Google Sheets API request specification for this method.

参考文献: