Python Excel date/time read in issue

 ̄綄美尐妖づ 提交于 2019-12-10 17:18:14

问题


I am trying to read dates/time off an excel sheet using Python, but I only want to read in the time so I can perform computations on it. For example if I have a date in the format: 3/11/2003 4:03:00 AM on my excel sheet how can I read in just the 4:03:00 in Python? I ultimately want to be able to subtract hours, mins, or seconds from the read in time.


回答1:


The best option would be to convert the date to datetime using xldate_as_tuple. Assuming you have an test.xls file with 3/11/2003 4:03:00 AM in the A1 cell:

from datetime import datetime, timedelta
import xlrd

book = xlrd.open_workbook(filename='test.xls')
sheet = book.sheet_by_name('Sheet1')

date = sheet.cell_value(0, 0)
datetime_value = datetime(*xlrd.xldate_as_tuple(date, 0))

print datetime_value  # prints 2003-11-03 04:03:00
print datetime_value.time()  # 04:03:00
print datetime_value - timedelta(hours=1)  # prints 2003-11-03 03:03:00

Hope that helps.



来源:https://stackoverflow.com/questions/17685191/python-excel-date-time-read-in-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!