【问题标题】:Update Googlesheet cell with timestamp from Python使用 Python 的时间戳更新 Googlesheet 单元格
【发布时间】:2019-02-15 01:33:52
【问题描述】:

我正在尝试使用 python 3.6.5 用我的机器的当前日期/时间更新 google 工作表中的单元格。我正在使用 gspread 连接到谷歌表。

如果我执行以下操作,它将给出我希望放入谷歌表格的日期/时间:

import datetime
print(datetime.datetime.now())
2018-09-10 10:50:38.171795

我正在努力弄清楚如何将该输出打印到谷歌表格中的单元格中。这是我的设置,最后一行是我想要弄清楚的:

import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials

#connect to google sheets through API
json_key = 'work.json'
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key, scope)
client = gspread.authorize(credentials)

#define googlesheet
rsheet = client.open_by_url('https://docs.google.com/spreadsheets/d/randomgooglesheetid')

#define the correct worksheet, index - 0 is the first sheet, 1 is the second...
engwsr = rsheet.get_worksheet(0)

engwsr.update_acell('O1' , print(datetime.datetime.now()))

最后一行只是将日期时间打印到 python 中,并没有更新谷歌表中的任何内容。我的目标是将“2018-09-10 10:50:38.171795”打印到单元格 O1 中。

有没有更好的方法来做到这一点?日期时间格式不必完全一样,只需使用日期和时间即可轻松读取。

【问题讨论】:

    标签: python python-3.x timestamp gspread


    【解决方案1】:

    代替

    engwsr.update_acell('O1' , print(datetime.datetime.now()))

    engwsr.update_acell('O1' , datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

    print() 没有返回值,这就是为什么您在工作表中看不到任何内容的原因。

    【讨论】:

      【解决方案2】:

      你可以使用这个功能,它对我有用:

      进口:

      import gspread
      import datetime
      

      让我们有一个变量 now 作为日期时间对象:

      now = datetime.datetime.now()
      

      然后将 now 作为字符串传递给以下函数。

      wb.values_update(
          'sheet1!A2',
          params={
              'valueInputOption': 'USER_ENTERED'
          },
          body={
              'values': [[str(now)]]
          }
      )
      

      这样您输入的日期时间将被 google sheet 识别,就好像它是由人输入的一样。 如果你想了解更多gspread的使用方法follow this link.

      也可以通过替换[[str(now)]]来输入多个值

      与:

      [[str(now) ,'b','c','d']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-26
        • 2014-08-11
        相关资源
        最近更新 更多