现在,我的 Excel2CSV 函数可以正常工作,但遇到了另一个问题,其中 Excel 文件中的日期字段(“打开日期”、“关闭日期”)在 Excel 中格式为日期,并被写入为整数值转换为 CSV 时 (例如 5/1/1995 转换为 34820)。
我希望它以纯文本形式写出这些日期(即 5/1/1995 - 或 - 1995 年 5 月 1 日,或类似的内容。人类可读的内容。)
def Excel2CSV(ExcelFile, SheetName, CSVFile):
import xlrd
import csv
print "Acquiring " + ExcelFile + "..."
workbook = xlrd.open_workbook(ExcelFile)
print "Locating " + SheetName + " Worksheet..."
worksheet = workbook.sheet_by_name(SheetName)
print "Creating " + CSVFile + "..."
csvfile = open(CSVFile, 'wb')
print "Preparing to write CSV file..."
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
print "Writing CSV..."
for rownum in xrange(worksheet.nrows):
wr.writerow(
list(x.encode('utf-8') if type(x) == type(u'') else x
for x in worksheet.row_values(rownum)))
print "Closing CSV File..."
csvfile.close()
print "CSV successfully written."
return CSVFile
我不确定如何按名称或值捕获日期字段,然后将值正确转换为纯文本。如有任何帮助,我们将不胜感激。
最佳答案
要将日期数字转换为 Python 日期时间
,请使用以下公式:
dt = datetime.datetime(1899, 12, 30) + datetime.timedelta(days=num)
完成后,您可以使用 str(dt)
将其转换为默认格式,或使用 dt.strftime(format)
指定您自己的格式。请参阅datetime
documentation
关于python - 将 Excel 转换为 CSV - 正确转换日期字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043370/