How to get correct date using gspread

王林
Release: 2024-02-09 13:00:04
forward
495 people have browsed it

如何使用 gspread 获取正确的日期

Question content

How to use Python’s gspread to get spreadsheet values?

Suppose there is a cell that looks like 1/1 because m/d is specified as the cell display format, but actually contains 2024/1/1. Retrieving this cell using get_all_values() returns "1/1". I want the actual value "2024/1/1", not the value shown on the worksheet. what do I do?

I will omit the worksheet acquisition part.

values ​​= workbook.worksheet(sheet_name).get_all_values()

value = values[1][0] # Get 1/1


Correct answer


Problems and solutions:

From the image, script, and current value you showed, I understand that you put the value of 2024/01/01 into cell "a2" as a date object. Also, the cell value is displayed as 1/1 in numeric format.

At the current stage, when retrieving that cell value via the sheets api, 1/1 will be retrieved as the default request for valuerenderoption: formatted_value. When valuerenderoption is modified to unformatted_value, the serial number of 45292 is obtained. Unfortunately, the entered 2024/01/01 value cannot be directly retrieved at this stage. Therefore, the following process requires it.

  1. Retrieve the sequence number from the cell using valuerenderoption: unformatted_value.
  2. Convert serial number to date object.
  3. Convert date format.

How about the following modification when this flow is reflected in your presentation script?

Modified script:

values = workbook.worksheet(sheet_name).get_all_values(value_render_option="UNFORMATTED_VALUE")
value = values[1][0]
date = datetime.fromtimestamp((int(value) - 25569) * 86400) # Ref: https://stackoverflow.com/a/6154953
formatted = date.strftime('%Y/%m/%d') # or date.strftime('%Y/%-m/%-d')  # or date.strftime('%Y/%#m/%#d')
print(formatted)
Copy after login
  • If the date object of cell "a2" is 2024/01/01, and 1/1 is displayed in numeric format, when running this script, formatted is 2024/01/01.

  • Use from datetime import datetime.

references:

The above is the detailed content of How to get correct date using gspread. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!