如何使用 xlrd 读取日期? [英] How to read dates using xlrd?
问题描述
这是使用rec"变量读取excel表中日期的代码,但其打印浮点值如何以日期格式打印,例如'2015:09:02'
This is the code where "rec" variable is used to read the dates in excel sheet but its printing float value how to print that in date format for example '2015:09:02'
for rec in sorted(out.keys()):
print rec #printing float values
print str(out[rec])
我得到了输出:
42240.0
24
推荐答案
Excel 在内部将日期值存储为浮点数.因此,在 xlrd 中,如果要将 Excel 日期值读取为 Python 日期值,则必须使用 xldate_as_tuple
方法来获取日期.
Excel internally stored date values as floats. So in xlrd if you want to read Excel date values as Python date values, you have to use the xldate_as_tuple
method to get the date.
文档:http://www.lexicon.net/sjmachin/xlrd.html#xlrd.xldate_as_tuple-function
这是一个通用示例:
import datetime, xlrd
book = xlrd.open_workbook("myexcelfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime
如果您创建文件 myexcelfile.xls
并在单元格 A1 中输入日期并运行上述代码,您应该能够在 a1_as_datetime
变量.
If you create the file myexcelfile.xls
and enter a date in cell A1 and run the above code, you should be able to see the correct datetime value in the a1_as_datetime
variable.
这篇关于如何使用 xlrd 读取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!