我想使用python连接数据从Excel到Google Sheet。
但是,我得到了错误 "TypeError.Object of type datetime is not JSON serializable"。类型为datetime的对象不是JSON可序列化的"
我猜测这个错误发生在 "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库不会序列化datetime对象。你必须自己做。找出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