반응형
xlrd를 사용하여 xls 파일을 읽고 있습니다. 문제는 xlrd가 "12/09/2012"와 같은 값을 읽을 때 "xldate : 41252.0"과 같은 결과를 얻는다는 것입니다. xlrd.xldate_as_tuple 을 사용하면 다음과 같은 결과가 나타납니다.
(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"를 어떻게 얻을 수 있습니까?
해결 방법
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
참조 페이지 https://stackoverflow.com/questions/16229610
반응형
'파이썬' 카테고리의 다른 글
파이썬 Gunicorn을 포트 80에서 실행하기 (0) | 2021.01.19 |
---|---|
파이썬 dict에서 값 목록을 어떻게 얻을 수 있습니까? (0) | 2021.01.19 |
파이썬 Python 디버깅 팁 (0) | 2021.01.18 |
파이썬 문자열에서 쉼표를 제거하는 방법 (0) | 2021.01.18 |
파이썬 1D 배열을 numpy 행렬로 변환 (0) | 2021.01.18 |
댓글