2013-04-26 4 views
8

의 원래 값을 xlrd. 이 "2012년 12월 9일" 같은 xlrd 판독 값이, 내가이 같은 결과를 얻을 때 문제가있다 "xldate : 41252.0". 내가 xlrd.xldate_as_tuple를 사용하는 경우,이 결과를 얻을 :내가 xlrd 사용 XLS 파일을 읽고 있어요 셀

(2016, 12, 10, 0, 0, 0)

내 코드 :

curr_row = -1 
while curr_row < num_rows: 
    curr_row += 1 
    row = worksheet.row(curr_row)  
     for x in xrange(num_cols): 
      field_type = worksheet.cell_type(curr_row, x) 
      if field_type == 3: # this is date 
       field_value = worksheet.cell_value(curr_row, x) 
       print worksheet.cell(curr_row, x).value 
       print xlrd.xldate_as_tuple(field_value, 1) 

결과 :

41252.0 
(2016, 12, 10, 0, 0, 0) 

모두 결과는 나에게 잘못이다. xlrd를 사용하여 원래의 셀 값 "12/09/2012"를 어떻게 얻을 수 있습니까?

답변

13

docstring에 따르면, 당신은 두 번째 매개 변수로 xldate_as_tuple에 통합 문서의 datemode을 통과해야합니다

from datetime import datetime 
import xlrd 


book = xlrd.open_workbook("test.xls") 
sheet = book.sheet_by_index(0) 
a1 = sheet.cell_value(rowx=0, colx=0) 

print a1 # prints 41252.0 
print xlrd.xldate_as_tuple(a1, 1) # prints (2016, 12, 10, 0, 0, 0) 

a1_tuple = xlrd.xldate_as_tuple(a1, book.datemode) 
print a1_tuple # prints (2012, 12, 9, 0, 0, 0) 

a1_datetime = datetime(*a1_tuple) 
print a1_datetime.strftime("%m/%d/%Y") # prints 12/09/2012 
+1

이 도움이! 하지만 원래 문자열 "12/09/2012"를 얻을 수있는 방법이 있습니까? – twoface88

관련 문제