尝试打印expensedate
时出现以下错误。
Traceback (most recent call last):
File "expense.py", line 36, in <module>
print_expense_month('nov16')
File "expense.py", line 31, in print_expense_month
print expensedate + " | " + description + " | " + "%.2f" % (cost)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'str'
第34行是下面的print
行。我只想打印日期。
while description is not None:
expensedate = sheet.cell(row = i, column = COLUMN_DATE).value
description = sheet.cell(row = i, column = COLUMN_DESCRIPTION).value
cost = sheet.cell(row=i, column=COLUMN_COST).value
#expensedate format = 2016-11-01 00:00:00
if description is not None:
print expensedate + " | " + description + " | " + "%.2f" % (cost)
i = i + 1
答案 0 :(得分:2)
如果您想要的只是打印件,请从
更改打印行print expensedate + " | " + description + " | " + "%.2f" % (cost)
到
print "%s | %s | %.2f" % (expensedate, description, cost)
答案 1 :(得分:1)
您的问题是,您尝试将datetime
类型添加到str
。在python中,您需要转换类型。
print str(expensedate) + " | " + description + " | " + "%.2f" % (cost)
如果您想要不同的日期时间格式,请使用strftime
https://docs.python.org/2/library/datetime.html#datetime.date.strftime
另外我建议使用string's format
而不是字符串连接,这是更多功能完整且没有类型问题
print "{} | {} | {:.2f}".format(expensedate, description, cost)