简体   繁体   English

我在使用python从Excel工作表中读取日期和时间时遇到问题

[英]I am having trouble in reading date and time from an excel sheet using python

import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0


for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')

i get output as 我得到的输出为
42753.61492 42753.61492
42753.61492 42753.61492
42753.61492 42753.61492
42753.61492 42753.61492
42753.61492 42753.61492

where i was looking something as this 我在看这样的东西
2017-01-18 14:45:29 a 2017-01-18 14:45:29一个
2017-01-18 14:45:29 a 2017-01-18 14:45:29一个
2017-01-18 14:45:29 a 2017-01-18 14:45:29一个
2017-01-18 14:45:29 a 2017-01-18 14:45:29一个
2017-01-20 09:10:06 a 2017-01-20 09:10:06 a

You just need to set the number format when you're writing the output workbook, the same as you would in Excel. 编写输出工作簿时,只需设置数字格式即可,就像在Excel中一样。 This is done by including another parameter on your outsheet.write() call. 这可以通过在outsheet.write()调用中包含另一个参数来完成。

Unfortunately the "official" documentation for xlwt is pretty difficult to use. 不幸的是,xlwt的“官方”文档很难使用。 Much better is the old tutorial PDF . 旧的教程PDF更好。 There you should read up on styles (XFStyle and easyxf). 在那里,您应该阅读样式(XFStyle和easyxf)。

Or even better still is to ditch xlwt altogether and switch to XlsxWriter , which is easier to use, has more features, has vastly better documentation , is actively maintained, and generates current .xlsx files instead of outdated .xls files. 甚至更好的办法是完全放弃xlwt并切换到XlsxWriter ,它更易于使用,具有更多功能,具有大大更好的文档 ,被积极维护并生成当前的.xlsx文件而不是过时的.xls文件。

>>> import datetime
>>> datetime.datetime(1899,12,30) + datetime.timedelta(days=42753.61492)
datetime.datetime(2017, 1, 18, 14, 45, 29, 88000)

Can you give try to this: 您能尝试一下吗:

from datetime import datetime
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0


for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,datetime.fromtimestamp(float(insheet.cell_value(row, col))))
    outrow += 1
wb.save(r'C:\combined.xls')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM