JSON 序列化错误 - 自动更新数据到 Google sheet

JSON serializable error - Automatically update data to Google sheet

我想使用 python 将数据从 Excel 连接到 Google Sheet。

但是我得到了错误"TypeError: Object of type datetime is not JSON serializable"

我猜错误的发生符合"wks.update_cells(cell_list)"。我可以知道如何解决这种错误吗?谢谢

import os
import pandas as pd
import glob
import datetime
import numpy as np
import time
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import json

def numberToLetters(q):
    q = q - 1
    result = ''
    while q >= 0:
        remain = q % 26
        result = chr(remain+65) + result;
        q = q//26 - 1
    return result


current_path = os.getcwd()
raw_df = pd.read_excel(glob.glob(os.path.join(current_path , 'Studio*'))[0],sheet_name = "Dashboard", encoding = "ISO-8859-1")
df = raw_df.replace(np.nan, '', regex=True)

scope = ['https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('startup_funding.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open("Testing_Dashboard_Upload").sheet1

wks.clear()
columns = df.columns.values.tolist()
# selection of the range that will be updated
cell_list = wks.range('A1:'+numberToLetters(len(columns))+'1')


# modifying the values in the range
for cell in cell_list:
    val = columns[cell.col-1]
#    if type(val) is str:
#        val = val.decode('utf-8')
    cell.value = val

# update in batch
wks.update_cells(cell_list)


#4. handle content

# number of lines and columns
num_lines, num_columns = df.shape
# selection of the range that will be updated
cell_list = wks.range('A2:'+numberToLetters(num_columns)+str(num_lines+1))
# modifying the values in the range
for cell in cell_list:
    val = df.iloc[cell.row-2,cell.col-1]
    if isinstance(val, (np.float64, np.int64, np.bool_ )):
#        val = np.asscalar(val)
#        DeprecationWarning: np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead 
        val = val.item()
    cell.value = val

#5. update in batch

wks.update_cells(cell_list)

Python json 库不会序列化日期时间对象。你必须自己做。找出cell_list中哪个值是datetime,并使用strftime方法将其转换为字符串。根据您的代码,我认为您正在将 cell.value 设置为 datetime 对象。如果是这样,您可以更改行

    cell.value = val

if isinstance(val, datetime.datetime):
    val = val.strftime("%m/%d/%Y, %H:%M:%S")
cell.value = val