2013-04-26 6 views
8

मैं xlrd का उपयोग कर xls फ़ाइल पढ़ रहा हूं। समस्या यह है कि, जब xlrd इस मान को "12/09/2012" जैसा मानते हैं, तो मुझे इस "xldate: 41252.0" जैसे परिणाम मिलते हैं। जब मैं xlrd.xldate_as_tuple उपयोग करते हैं, मैं इस परिणाम मिलता है:xlrd सेल का मूल मान

(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

संबंधित मुद्दे