将 xldate 转换为 python 日期时间 [英] convert xldate to python datetime

查看:49
本文介绍了将 xldate 转换为 python 日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用以下代码将 excel xldate 转换为 python datetime 时遇到问题.这是正确的转换方式吗?

I have a problem converting excel xldate to python datetime with the following code. Is this the right way to convert?

import xlrd
from datetime import datetime

book = xlrd.open_workbook("a.xls")
sh = book.sheet_by_index(0)
for rx in range(1,sh.nrows):
    a = sh.row(rx)
    print a  
    year, month, day, hour, minute = xlrd.xldate_as_tuple(a[0], book.datemode)
    py_date = datetime.datetime(year, month, day, hour, minute)

<小时>

a 被打印 -->


a is printed -->

   [xldate:40544.0, number:0.0, number:75.49847785316135, number:75.6401124106301]

<小时>

显示以下错误


The below error is shown

  year, month, day, hour, minute = xlrd.xldate_as_tuple(a[0], book.datemode)

  File "C:\Anaconda\Lib\site-packages\xlrd\xldate.py", line 67, in xldate_as_tuple
    xldays = int(xldate)
  TypeError: int() argument must be a string or a number, not 'Cell'

推荐答案

a[0] 是一个 xlrd.Cell,所以需要使用a[0].value来访问cell内容.

a[0] is a xlrd.Cell, so you need to use a[0].value to access the cell content.

另外,你不能解压到年、月、日、小时、分钟,因为生成的元组中有五个以上的值(second呢?) 但是,您可以通过使用元组解包来避免这种情况(参见例如 **(双星)和 *(星)对参数有何作用?) 而不是临时变量:

Also, you can't unpack to year, month, day, hour, minute because there are more than five values in the tuple produced (what about second?) However, you can avoid that by using tuple unpacking (see e.g. What does ** (double star) and * (star) do for parameters?) instead of the temporary variables:

py_date = datetime.datetime(*xlrd.xldate_as_tuple(a[0].value,
                                                  book.datemode))

这篇关于将 xldate 转换为 python 日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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