[英]how to join tuple datetime
我是Python的新手,它試圖將Oracle表中的一些數據添加到數組中,並添加另一個值作為datetime(字符串)進行記錄。
我的代碼是:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
con = cx_Oracle.connect('user', 'pass', dsn_tns)
q='SELECT columns FROM table'
device_status = []
cursor = con.cursor()
cursor.execute(q)
results = cursor.fetchall()
for row in results:
device_status.append(row + tuple(now))
con.close()
print device_status[1]
這是輸出:
('1110', '1000074', 2060, '2', '0', '1', '7', '-', '0', '2', '-', '2', '3', ' ', '1', '1', ':', '5', '2', ':', '0', '2')
我想加入日期,所以輸出將如下所示:
('1110', '1000074', 2060,'2017-02-23 11:57:41')
嘗試使用連接,但出現以下錯誤:
can only concatenate tuple (not "str") to tuple
我究竟做錯了什么?
編輯:我了解到您可以按索引訪問元組元素。 您可以執行以下操作:
>>> a
('1110', '1000074', 2060, '2', '0', '1', '7', '-', '0', '2', '-', '2', '3', ' ', '1', '1', ':', '5', '2', ':', '0', '2')
>>> print(a[0], a[1], a[2], (''.join(a[3:])))
('1110', '1000074', 2060, '2017-02-23 11:52:02')
然后,您可以將此值附加到device_status
列表。
這取決於前3個值始終是您要查找的類型,而從索引3開始始終是日期和時間值。 希望這可以幫助。
零錢
for row in Results:
device_status.append(row + (now,))
^
,
這使它成為一個元組。 因此兩者都成為元組。
然后tuple(now)
會像這樣拆分所有值,
In [42]: a = '2017-02-23 11:57:41'
In [43]: print tuple(a)
('2', '0', '1', '7', '-', '0', '2', '-', '2', '3', ' ', '1', '1', ':', '5', '7', ':', '4', '1')
看到工作,
In [34]: time_
Out[34]: '2017-02-23 15:33:42.353505'
In [35]: (1,2,45.7,799)+(time_,)
Out[35]: (1, 2, 45.7, 799, '2017-02-23 15:33:42.353505')
In [36]: (1,2,45.7,799)+(time_) # tried with out , and gets an error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-551a4c2dc8d7> in <module>()
----> 1 (1,2,45.7,799)+(time_)
TypeError: can only concatenate tuple (not "str") to tuple
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.