Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python xlrd-将Excel时间转换为mysql日期格式?_Python_Excel_Xlrd - Fatal编程技术网

Python xlrd-将Excel时间转换为mysql日期格式?

Python xlrd-将Excel时间转换为mysql日期格式?,python,excel,xlrd,Python,Excel,Xlrd,我有这个密码 from xlrd import open_workbook import csv wb = open_workbook('test.xlsm') for i in range(2, wb.nsheets): sheet = wb.sheet_by_index(i) print (sheet.name) with open("data/%s.csv" %(sheet.name.replace(" ","")), "w") as file:

我有这个密码

from xlrd import open_workbook
import csv

wb = open_workbook('test.xlsm')

for i in range(2, wb.nsheets):
    sheet = wb.sheet_by_index(i)
    print (sheet.name)
    with open("data/%s.csv" %(sheet.name.replace(" ","")), "w") as file:
        writer = csv.writer(file, delimiter = ",")
        print (sheet, sheet.name, sheet.ncols, sheet.nrows)

        header = [cell.value for cell in sheet.row(0)]
        writer.writerow(header)

        for row_idx in range(1, sheet.nrows):
            row = [int(cell.value) if isinstance(cell.value, float) else cell.value
                   for cell in sheet.row(row_idx)]
            writer.writerow(row)

代码运行良好,但是在csv文件中,我有多个列中的excel日期,但是脚本将所有内容转换为excel时间,是否有方法指定a、D、F、E、G、H列将excel日期转换为正常的mysql日期?

我不知道mysql日期,但我相信,一旦你有了Python日期,你就可以想出如何获得这些。要获取Python日期,请使用
xlrd
中的
xldate\u as\u datetime
函数。而不是

int(cell.value)
你需要使用

xlrd.xldate_as_datetime(cell.value, wb.datemode)
对于您知道的日期值。根据你的评论,你知道哪些是日期。但如果事先不知道,可以测试Excel单元格类型:

if cell.ctype == xlrd.XL_CELL_DATE:
    mydate = xlrd.xldate_as_datetime(cell.value, wb.datemode)

我不想为你重写你的代码。您应该能够将此答案中的信息合并到您的程序中。

xlrd未维护,仅当您必须处理旧的XLS格式时才应使用。@AMC-我强烈反对
xlrd
是一个成熟的软件包,它工作得非常好,在某些方面优于
openpyxl
。没有理由避免使用
xlrd
@JohnY,而且在某些方面比openpyxl好。我更喜欢
xlrd
,主要是因为我更喜欢它的API,尽管这当然是主观的。它也更小、更简单,并且不引入任何依赖项。如果需要加载所有数据,则效率更高
openpyxl
当然有它的优点,人们应该可以随意使用这两个包。如果你需要读写同一本工作簿,很难打败
openpyxl
。我很少这样做,我更喜欢
xlsxwriter
的编写API和
xlrd
的阅读API。我不得不承认
xlrd
API在某些地方比较笨重,提取日期是其中的主要部分。