简体   繁体   中英

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.

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.

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. 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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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