25

Possible Duplicate:
How do I read a date in Excel format in Python?

My date can be among any field in an excel file but when I read it using python xlrd its being read as a float. Is there a way to read all the excel cells as string?

I want to prepare a script to generate a file having all the values in excel file separated by a pipe but this date thing is creating problem.

2
  • can you post your current code and some sample data? Commented Dec 19, 2012 at 23:22
  • @Linuxios You definitely misunderstood. Excel stores dates as floats. For example, 11-1-88 is stored as 32448.0. Commented Dec 19, 2012 at 23:30

1 Answer 1

78

Excel stores dates as floats. If you want to convert them xlrd has a function to help you with this: xldate_as_tuple

An exmple:

import datetime, xlrd
book = xlrd.open_workbook("myfile.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
Sign up to request clarification or add additional context in comments.

5 Comments

@dedoco....is there any way to edit date mode so that in output we have date in mm/dd/yyyy format.
@KundanKumar datetimehas a variety of output options, to my knowledge (I'm not very familiar with datetime) the closes format to what you want is the ISO 8601 format (YYYY-MM-DD) which you get by: a1_as_datetime.date().isoformat()
@KundanKumar the point is, excel stores only the float, so if you want to print the date in a readable format, I'm afraid you will have to convert it first. There is no way around this. ...if you are happy with my answer, please consider to mark it as the right answer ;).
Late to the party, but for anyone dropping by: add .strftime("%m/%d/%Y") behind the datetime() method for the mm/dd/yyyy format @KundanKumar is asking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.