问题
I would like to use python to connect data from Excel to Google Sheet.
But I got error "TypeError: Object of type datetime is not JSON serializable"
I guess the error happened in line with "wks.update_cells(cell_list)". May I know how to solve this kind of error? Thank you
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)
回答1:
Python json library wont serialize datetime object. You have to do it yourself. Find out which value in cell_list is datetime, and convert it to string using strftime method. From your code I think you are setting cell.value to a datetime object. If that so, you may change the line
cell.value = val
to
if isinstance(val, datetime.datetime):
val = val.strftime("%m/%d/%Y, %H:%M:%S")
cell.value = val
来源:https://stackoverflow.com/questions/61382337/json-serializable-error-automatically-update-data-to-google-sheet