Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Googlesheet cell with timestamp from Python

I'm attempting to update a cell in a google sheet with the current date/time of my machine using python 3.6.5. I'm using gspread to connect to the google sheet.

If I do the following it will give the date/time that I'm looking to put into google sheets:

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

I'm struggling to figure out how to get that output to be printed into a cell in google sheets. Here's my setup and then the last line is what I'm trying to figure out:

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()))

This last line just prints the datetime into python and doesn't update anything in the google sheet. My goal is to have '2018-09-10 10:50:38.171795' printed into cell O1.

Is there some better way to do this? The datetime format doesn't have to be exactly like that, just something easily readable with the date and time.

like image 701
C.Felix Avatar asked Sep 10 '18 15:09

C.Felix


People also ask

How do you automatically populate a date in Google Sheets when a cell is updated?

Control + Shift + : (hold the Control and Shift keys and press the colon key). Note that these keyboard shortcuts would insert a static date and time value. This means that if you make any changes in the worksheet or close and open it, these date/time values will not change.

Can you timestamp a cell in Google Sheets?

Insert Timestamp in Google SheetsFor static timestamps, you can also use CTRL + ; and CTRL + : to insert the date or time. However, Google Sheets has a keyboard shortcut that Excel doesn't – CTRL + ALT + SHIFT + ; (Control Alt Shift Semicolon). This inserts a static date and time into the selected cell.


1 Answers

Instead of

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

put

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

print() has no return value, that is why you do not see anything in your sheet.

like image 182
Andrea Nagy Avatar answered Oct 28 '22 01:10

Andrea Nagy