443,846 Members | 1,836 Online Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

# Reading time field from excell sheet by python?

 P: 30 Hi, How do i read time field from excell sheet by python. I am getting "0.400694444444" value but sheet has "9:37:00 AM" . How to convert it ? Regards, Ashok Feb 13 '09 #1
3 Replies

 Expert Mod 2.5K+ P: 2,851 The excel value represents the time as a portion of one day starting at midnight. There are 86400 seconds in one day, 60 seconds in one minute, and 60 minutes in one hour. Expand|Select|Wrap|Line Numbers def convert_excel_time(t, hour24=True):     if t > 1:         t = t%1     seconds = round(t*86400)     minutes, seconds = divmod(seconds, 60)     hours, minutes = divmod(minutes, 60)     if hour24:         if hours > 12:             hours -= 12             return "%d:%d:%d PM" % (hours, minutes, seconds)         else:             return "%d:%d:%d AM" % (hours, minutes, seconds)     return "%d:%d:%d" % (hours, minutes, seconds)   print convert_excel_time(0.400983796) print convert_excel_time(0.900983796, hour24=False) print convert_excel_time(0.4006944444444) print convert_excel_time(1.4006944444444) Output: Expand|Select|Wrap|Line Numbers >>> 9:37:25 AM 21:37:25 9:37:0 AM 9:37:0 AM >>>  Feb 13 '09 #2

 P: 30 more simple solution import datetime print datetime.timedelta(0.400694444444) Now i am faceing another problem, I want to write the time into next column, but i am getting this below error. self._cell_types[rowx][colx], IndexError: array index out of range Any solution? Feb 17 '09 #3

 Expert Mod 2.5K+ P: 2,851 @ashokd001 True, but datetime.timedelta returns hours:minutes:seconds only so you lose AM and PM. @ashokd001 You have not posted your code, so I have no idea how you are reading from or writing to an Excel file. win32com.client.Dispatch() is the only way I am a bit familiar with. Expand|Select|Wrap|Line Numbers import datetime import win32com.client application = win32com.client.Dispatch("Excel.Application") application.Visible=0 wb = application.Workbooks.Open("yourapp.xls") t = wb.Worksheets("Sheet3").Range("A1").Value wb.Worksheets("Sheet3").Range("B1").Value = str(datetime.timedelta(t)) wb.Close(SaveChanges=1) application.Quit()   Feb 17 '09 #4 