Python xlrd two methods for reading excel date types
This article mainly introduces two ways for Python xlrd to read the excel date type. This article also describes how to read a cell in excel by xlrd. For more information, see
There is an excle table that needs to be filtered and written to the database, but the cell of the date type is a number, so the solution is queried.
Basic code structure
The Code is as follows:
Data = xlrd. open_workbook (EXCEL_PATH)
Table = data. sheet_by_index (0)
Lines = table. nrows
Cols = table. ncols
Print u 'the total line is % s, cols is % s' % (lines, cols)
Read a cell:
The Code is as follows:
Table. cell (x, y). value
X: Line
Y: Column
Rows and columns start from 0
* Time type conversion: Convert the excel time to python time (two methods)
Excel: A Cell
The Code is as follows:
Xlrd. xldate_as_tuple (table. cell (). value, 0) # convert to the tuples
(2014, 7, 8, 0, 0, 0)
Xlrd. xldate. xldate_as_datetime (table. cell (). value, 1) # directly convert to datetime object
Datetime. datetime (2018, 7, 9, 0, 0)
Table. cell (2, 2). value # No Conversion
41828.0
View Source Code:
The Code is as follows:
# @ Param xldate The Excel number
# @ Param datemode 0: 1900-based, 1: 1904-based.
Xldate_as_tuple (xldate, datemode)
Input a cell of the date type will return a time structure consisting of tuples, you can set up a time type according to this tuples
Datemode has two options. Basically, we use the 1900-based timestamp.
The Code is as follows:
##
# Convert an Excel date/time number into a datetime. datetime object.
#
# @ Param xldate The Excel number
# @ Param datemode 0: 1900-based, 1: 1904-based.
#
# @ Return a datetime. datetime () object.
#
Def xldate_as_datetime (xldate, datemode)
The input parameter is the same as the preceding one, but the return value is of the datetime type, so you do not need to convert it yourself.
Of course, both functions have corresponding inverse functions, which convert the python type to the corresponding excle time type.