简体   繁体   English

如何加入元组datetime

[英]how to join tuple datetime

I'm new with Python and trying to add some data from an Oracle table to an array and add another value as datetime (string) for record. 我是Python的新手,它试图将Oracle表中的一些数据添加到数组中,并添加另一个值作为datetime(字符串)进行记录。

My code is: 我的代码是:

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]

This is the output: 这是输出:

('1110', '1000074', 2060, '2', '0', '1', '7', '-', '0', '2', '-', '2', '3', ' ', '1', '1', ':', '5', '2', ':', '0', '2')

I want to join the date so the output will look like: 我想加入日期,所以输出将如下所示:

('1110', '1000074', 2060,'2017-02-23 11:57:41')

Tried to use join but got the following error: 尝试使用连接,但出现以下错误:

can only concatenate tuple (not "str") to tuple

What am I doing wrong? 我究竟做错了什么?

Edited: I learned you can access tuple elements by index. 编辑:我了解到您可以按索引访问元组元素。 You could do something like this: 您可以执行以下操作:

>>> 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')

You could then append this value to the device_status list. 然后,您可以将此值附加到device_status列表。

This relies on the first 3 values always being of the type you're looking for and from index 3 onwards being a date and time value. 这取决于前3个值始终是您要查找的类型,而从索引3开始始终是日期和时间值。 Hope this helps. 希望这可以帮助。

A small change, 零钱

for row in Results:
    device_status.append(row + (now,))
                                   ^

, this make which as a tuple. ,这使它成为一个元组。 So both are become tuple. 因此两者都成为元组。

And tuple(now) will split all the values like this, 然后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')

See the working, 看到工作,

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