从 Excel 文件中读取日期会将其转换为类似 32509.0 的数字

Reading a date from an Excel file converts it to a number like 32509.0

当我使用 xlrd 包从 Excel 文件中读取日期时,导入的数据不是日期而是像 32509.0.

这样的数字

Excel 输入数据是像 1989-01-01 这样的日期。

代码:

import xlrd
import mysql.connector
import datetime

name= "Anand1989.xls"
book=xlrd.open_workbook(name)
worksheet = book.sheet_by_index(0)
database = mysql.connector.connect (host="localhost", user = "root", passwd = "", db = "rainfall")
cursor = database.cursor()
query = """INSERT INTO  Anand1989(DATE) VALUES (%s)"""
for r in range(1, worksheet.nrows):
    DATE = worksheet.cell(r,0).value
    date_time_obj = datetime.datetime.strptime(str(DATE), '%Y-%m-%d').date
    values = (date_time_obj)
cursor.execute(query, values)
cursor.close()
database.commit()
database.close() 
print ("All Done! Bye, for now.")
Traceback (most recent call last):
File "newins.py", line 46, in <module> date_time_obj = datetime.datetime.strptime(str(DATE), '%Y-%m-%d').date
File "C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetimet tt, fraction,gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime (data_string, format)) ValueError: time data '32509.0' does not match format '%Y-%m-%d'

在Excel中,日期是数字,1/1/1900 相当于 1。因此数字 32509 表示对应于 1/1/1900 或 1/1/1989 之后的 32508 天的日期(小数部分对应时间)。

您可以使用 xlrd.xldate.xldate_as_tuple(Excel日期,日期模式)

其中:

Excel日期:表示日期时间的十进制数。

datemode 为 0:基于 1900 或 1:基于 1904(在本例中应为 0)

和returns格式的元组(年、月、日、时、分,nearest_second)