以 10 为底的 int() 的 xlrd 无效文字

xlrd invalid literal for int() with base 10

我需要解析一个包含数据格式 'Tuesday, January 3, 2012 2:46pm' 的单元格。下面的代码给出了错误

invalid literal for int() with base 10: 'Tuesday, January 3, 2012 2:46pm'

我可以知道将此字符串解析为日期时间的正确方法是什么吗?

book = xlrd.open_workbook(f)
sh = book.sheet_by_index(0)
for rx in range(1, 10):  #sh.nrows
    m = sh.row(rx)
    print datetime(xlrd.xldate_as_tuple(m[0].value, book.datemode))

回溯

File "C:\Anaconda\Lib\site-packages\xlrd\xldate.py", line 67, in xldate_as_tuple
    xldays = int(xldate)
ValueError: invalid literal for int() with base 10: 'Tuesday, January 3, 2012 2:46pm'

你在找这个吗?

In [8]: from dateutil import parser

In [9]: dt = parser.parse('Tuesday, January 3, 2012 2:46pm')

In [10]: print dt
2012-01-03 14:46:00

首先,我不认为 m[0] 有一个 xldate 值,看起来它是以字符串形式出现的。

@Sait 的回答很好。但是如果你不想使用 dateutil ,你可以像这样使用 datetime.datetime.strptime() 函数 -

datetime.strptime('Tuesday, January 3, 2012 2:46pm', '%A, %B %d, %Y %H:%M%p')

你的情况 -

print datetime.strptime(m[0].value, '%A, %B %d, %Y %H:%M%p')