By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,836 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
3 Replies


bvdet
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
  1. def convert_excel_time(t, hour24=True):
  2.     if t > 1:
  3.         t = t%1
  4.     seconds = round(t*86400)
  5.     minutes, seconds = divmod(seconds, 60)
  6.     hours, minutes = divmod(minutes, 60)
  7.     if hour24:
  8.         if hours > 12:
  9.             hours -= 12
  10.             return "%d:%d:%d PM" % (hours, minutes, seconds)
  11.         else:
  12.             return "%d:%d:%d AM" % (hours, minutes, seconds)
  13.     return "%d:%d:%d" % (hours, minutes, seconds)
  14.  
  15. print convert_excel_time(0.400983796)
  16. print convert_excel_time(0.900983796, hour24=False)
  17. print convert_excel_time(0.4006944444444)
  18. print convert_excel_time(1.4006944444444)
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> 9:37:25 AM
  2. 21:37:25
  3. 9:37:0 AM
  4. 9:37:0 AM
  5. >>> 
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

bvdet
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
  1. import datetime
  2. import win32com.client
  3. application = win32com.client.Dispatch("Excel.Application")
  4. application.Visible=0
  5. wb = application.Workbooks.Open("yourapp.xls")
  6. t = wb.Worksheets("Sheet3").Range("A1").Value
  7. wb.Worksheets("Sheet3").Range("B1").Value = str(datetime.timedelta(t))
  8. wb.Close(SaveChanges=1)
  9. application.Quit()
  10.  
Feb 17 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.