在保持时间戳的同时将XLSX转换为CSV

我试图将一个完整的XLSX文件目录转换为CSV。 除了遇到包含时间信息的列的问题,一切正常。 XLSX文件正在由另一个我无法修改的程序创build。 但是我希望保持与在Excel中查看XLSX文件时所显示的时间相同的时间,并将其转换为CSV并在任何文本编辑器中查看。

我的代码:

import csv import xlrd import os import fnmatch import Tkinter, tkFileDialog, tkMessageBox def main(): root = Tkinter.Tk() root.withdraw() print 'Starting .xslx to .csv conversion' directory = tkFileDialog.askdirectory() for fileName in os.listdir(directory): if fnmatch.fnmatch(fileName, '*.xlsx'): filePath = os.path.join(directory, fileName) saveFile = os.path.splitext(filePath)[0]+".csv" savePath = os.path.join(directory, saveFile) workbook = xlrd.open_workbook(filePath) sheet = workbook.sheet_by_index(0) csvOutput = open(savePath, 'wb') csvWriter = csv.writer(csvOutput, quoting=csv.QUOTE_ALL) for row in xrange(sheet.nrows): csvWriter.writerow(sheet.row_values(row)) csvOutput.close() print '.csv conversion complete' main() 

要添加一些细节,如果我在Excel中打开一个文件,我在时间列中看到这个:

 00:10.3 00:14.2 00:16.1 00:20.0 00:22.0 

但是,我转换为CSV后,我看到在相同的位置:

 0.000118981 0.000164005 0.000186227 0.000231597 0.000254861 

感谢seanmhanson与他的答案https://stackoverflow.com/a/25149562/1858351我能够发现,Excel是倾倒的时间作为一天的小数。 虽然我应该尝试学习和更好地使用xlrd,但对于短期的修复,我可以将其转换成秒,然后从几秒钟恢复到最初看到的HH:MM:SS的时间格式。 我的(可能是丑陋的)代码下面的情况下,任何人都可以使用它:

 import csv import xlrd import os import fnmatch from decimal import Decimal import Tkinter, tkFileDialog def is_number(s): try: float(s) return True except ValueError: return False def seconds_to_hms(seconds): input = Decimal(seconds) m, s = divmod(input, 60) h, m = divmod(m, 60) hm = "%02d:%02d:%02.2f" % (h, m, s) return hm def main(): root = Tkinter.Tk() root.withdraw() print 'Starting .xslx to .csv conversion' directory = tkFileDialog.askdirectory() for fileName in os.listdir(directory): if fnmatch.fnmatch(fileName, '*.xlsx'): filePath = os.path.join(directory, fileName) saveFile = os.path.splitext(filePath)[0]+".csv" savePath = os.path.join(directory, saveFile) workbook = xlrd.open_workbook(filePath) sheet = workbook.sheet_by_index(0) csvOutput = open(savePath, 'wb') csvWriter = csv.writer(csvOutput, quoting=csv.QUOTE_ALL) rowData = [] for rownum in range(sheet.nrows): rows = sheet.row_values(rownum) for cell in rows: if is_number(cell): seconds = float(cell)*float(86400) hms = seconds_to_hms(seconds) rowData.append((hms)) else: rowData.append((cell)) csvWriter.writerow(rowData) rowData = [] csvOutput.close() print '.csv conversion complete' main() 

Excel将时间存储为天数。 您需要使用XLRD来确定单元格是否为date,然后根据需要进行转换。 我对XLRD不是很好,但是你可能想要类似这样的东西,如果你想保持前导零,改变string格式:

 if cell.ctype == xlrd.XL_CELL_DATE: try: cell_tuple = xldate_as_tuple(cell, 0) return "{hours}:{minutes}:{seconds}".format( hours=cell_tuple[3], minutes=cell_tuple[4], seconds=cell_tuple[5]) except (any exceptions thrown by xldate_as_tuple): //exception handling 

XLRDdate元组方法的文档可以在这里find: https ://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966#xldate.xldate_as_tuplefunction

对于已经回答的类似问题,请参阅以下问题: Python:xlrd从浮点数辨别date