I have a spreadsheet that have dates formatted as "Jan 30" etc, but have actual date values.
I fetch the data using python google Sheets API like so:
def get_spreadsheet_sheets(service, spreadsheetId):
spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheetId).execute()
dateCell = "C15"
for sheet in spreadsheet['sheets']:
sheetTitle = sheet['properties']['title']
rangeName = "%s!%s" % (sheetTitle, dateCell)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values',[])
values gives me 'Jan 30', I would like to actually read it as 1/30/2017
.. How can I do that?
Digger deeper into the spreadsheets.value.get http documentation (which corresponds to the python api client method references here I learned that I can put the option of valueRenderOption
as UNFORMATTED_VALUE
..
however when I run that I get this weird number for Jan 30
: 42765
what format is that number exactly? I know it's not a unix time stamp b/c converting it returns a non-sensical date
this code works but using python date formatting (it also assumes that the year is the current year.. but obviously that won't always be the case):
def get_spreadsheet_sheets(service, spreadsheetId):
spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheetId).execute()
dateCell = "C15"
for sheet in spreadsheet['sheets']:
sheetTitle = sheet['properties']['title']
rangeName = "%s!%s" % (sheetTitle, dateCell)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values',[])
dateStr = "%s %s" % (values[0][0], datetime.date.today().year)
cellDate = datetime.datetime.strptime(dateStr, '%b %d %Y')
print(cellDate)
To get dates, change the cell format to Date. If providing an explicit string input to DATEVALUE rather than a cell reference, surrounding quotation marks are required. Some date formats are not understood by Google Sheets.
The "weird number" it's called "serialized date-time value" or "date serial value". The 0 value displayed as date (yyyy-mm-dd) is 1899-12-30
. Integers are days, fractions are hours, minutes, etc.
Related: Converting Google spreadsheet date into a JS Date object?
References:
h/t Sam Berlin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With