[英]Python TypeError: 'datetime.datetime' object is not subscriptable
[英]TypeError:'datetime.datetime' object is not subscriptable
#!/usr/bin/env python
# coding: utf-8
import MySQLdb
import os,sys
import time
import datetime
from pyExcelerator import *
def main():
'''get datas from mysql to excel'''
w=Workbook()
ws=w.add_sheet('user')
mysql_conn=MySQLdb.connect(................,charset="utf8")
cursor=mysql_conn.cursor()
cursor.execute("select * from students")
results=cursor.fetchall()
results_count=len(results)
cursor.close()
mysql_conn.close()
a=results_count-1
print a
#print results
row=0
for r in results:
r3=[(x[0:2],x[2],x[3:]) for x in r]
w3=datetime.strptime("%Y-%m-%d %H:%M:%S")
[ws.write(x[0:2],i) for i in r3]
[ws.write(w3,i) for i in r3]
[ws.write(x[3:],i or '') for i in r3]:
row+=1
w.save('data.xls')
if __name__ == "__main__":
main()
我想從mysql到excel獲取數據,但r3=[(x[0:2],x[2],x[3:]) for x in r]
給我TypeError:'datetime.datetime' object is not subscriptable
。
我不知道該怎么辦,我只學習了3個星期,請幫助我嗎?
x
是datetime.datetime
對象,不能與x[0:2]
的[]表示法一起使用。
這意味着您的一列中包含一個日期對象,該對象必須以不同的方式進行解析。
首先,您不想使用pyExcelerator-它很舊,並且在3年的奇數年內沒有進行過更新(已被取代)。
您應該使用的是http://www.python-excel.org/上的實用程序,它提供了用於處理日期時間的功能。 自某個時期以來,Excel將它們存儲為浮點數。 有關信息, 請參見“ Excel電子表格中的日期”部分下的https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html 。 另請參閱https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#xldate.xldate_as_tuple-function,以了解如何將日期的Excel表示形式轉換為標准python日期時間。
如果您easy_install / pip xlutils,則將同時獲得xlrd(讀取)和xlwt(寫入)庫。 最多支持2003版文件,但2007 +(。xlsx文件)支持即將退出Beta版。
編輯
忘記提及https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html描述了xlwt庫如何獲取datetime.dateime
並將其轉換為Excel單元格。
表中的字段之一似乎包含datetime
對象, MySQLdb
還將它們作為datetime
返回。 您可能想先將datetime
轉換為str
。 通過使用分片,該行似乎占用了datetime
的一部分。 您可以使用datetime.strftime
實現相同的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.