写入 google sheet 时,我得到 Object of type Decimal is not JSON serializable

When writing to google sheet, I get Object of type Decimal is not JSON serializable

我正在尝试将日期框架写入 google sheet。我按照 sheets Python API 页面中的说明进行操作,但出现了一个奇怪的错误。

数据帧为十进制值,像这样

USD        ORDERS_AVG     DATE
316.60     123.0          2022-05-05 12:30:47.624000-07:00

使用以下代码,我试图在 google sheet 上编写:

try:
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
    SERVICE_ACCOUNT_FILE = 'key.json'

    creds = None
    creds = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    SAMPLE_SPREADSHEET_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
    service = build('sheets', 'v4', credentials=creds)
    sheet = service.spreadsheets()
except HttpError as err:
    print(err)

if df is not None and sheet:
    lol = df.values.tolist()
    try:
        clear_request = service.spreadsheets().values().clear(
            spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Data!A2:S")
        clear_response = clear_request.execute()
        print(clear_response)
        request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                        range="Data!A2", valueInputOption="USER_ENTERED", body={"values": lol}).execute()
        print(request)
    except HttpError as err:
        print(err)

但是除非我使用 .astype(str) 将整个数据帧转换为字符串,否则我会收到以下错误:

Traceback (most recent call last):
  File "dev2.py", line 107, in <module>
    request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/site-packages/googleapiclient/discovery.py", line 1094, in method
    headers, params, query, body = model.request(
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/site-packages/googleapiclient/model.py", line 160, in request
    body_value = self.serialize(body_value)
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/site-packages/googleapiclient/model.py", line 273, in serialize
    return json.dumps(body_value)
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/alainmore/anaconda3/envs/slot_alerts_env/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

问题是我不想将十进制值转换为字符串。我需要在 Google Sheet.

中将数字保留为数字,将日期保留为日期

我做错了什么?

------编辑 1

如果我打印 df.values.lolist(),我得到这个:

[Decimal('91.21'), Decimal('4.1'), Timestamp('2022-05-05 14:30:11.601000-0700', tz='America/Los_Angeles')], 
[Decimal('122.04'), Decimal('2.23'), Timestamp('2022-05-05 14:30:11.601000-0700', tz='America/Los_Angeles')], 
[Decimal('118.83'), Decimal('5.00'), Timestamp('2022-05-05 14:30:11.601000-0700', tz='America/Los_Angeles')], 
[Decimal('1591.61'), Decimal('28.00'), Timestamp('2022-05-05 14:30:11.601000-0700', tz='America/Los_Angeles')], 
[Decimal('97.43'), Decimal('3.02'), Timestamp('2022-05-05 14:30:11.601000-0700', tz='America/Los_Angeles')]]

示例数据框:

x = datetime.datetime.now()  

data = {'USD':[2219.48, 392.01, 16211.63, None],
        'ORDERS':[167.00, 10.00, 572.00, None],
        'DATE':[x,x,x,x]}
df = pd.DataFrame(data)

好吧,这是一个非常愚蠢的解决方案。似乎我正在写的 google sheet 设置了哥伦比亚的语言环境,其中使用小数点逗号,而不是小数点......所以像 53.00 这样的值被认为是一个字符串。 .. 更改区域设置后,我能够将数据框保存为字符串,并且 google sheets 自动识别带小数的数值。