繁体   English   中英

如何加入元组datetime

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM