Python Excel日期/时间已读问题 [英] Python Excel date/time read in issue

查看:206
本文介绍了Python Excel日期/时间已读问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python从Excel表中读取日期/时间,但我只想读取时间,以便我可以执行计算。例如,如果我有以下格式的日期: 3/11/2003 4:03:00 AM
在我的excel表上如何读取只是在Python中的 4:03:00 我最终希望能够从阅读时间中减去小时,最少或几秒。

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.

推荐答案

最好的选择是使用 datetime sjmachin / xlrd.html#xlrd.xldate_as_tuple功能> xldate_as_tuple 。假设你有一个 test.xls 文件与 3/11/2003 4:03:00 AM 在code> A1 cell:

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

希望有所帮助。

这篇关于Python Excel日期/时间已读问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆