How to convert tuple type to int on python?
43,489
Solution 1
What you have there is a tuple inside a tuple. So you want the first item of the outer tuple, which is u_data[0]
: the innermost tuple. And then you want the first item of that, which is u_data[0][0]
. That's a float
, so to get an integer, you want to wrap the whole thing in int()
, leading us to:
int(u_data[0][0])
Solution 2
In case the result set consists of more than one timestamp, you can get a list of timestamp(s) by:
...
u_data, _ = cursor.fetchall()
u_data = [int(_) for _ in udata]
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on July 31, 2022Comments
-
Admin almost 2 years
I'm Python beginner. I want to convert sqlcommand result (
tuple
type) intoint
type. How can i do that?import MySQLdb db = MySQLdb.connect("localhost","root","password","database") cursor = db.cursor() cursor.execute("SELECT timestamp FROM unixdb") u_data = cursor.fetchall() >>> print u_data ((1424794931452.0,),)
u_data
type istuple
and I want to getint
type from it. -
Mike Williamson almost 7 yearsIs this really the best answer? In this case, it works. But presumably the OP wanted a means by which to extract a singlet from a tuple / list of any arbitrary depth? Perhaps I'm trying to over-generalize, but it seems there must be a function to unravel an arbitrary depth, isn't there?
-
kindall over 6 yearsSure there is: the one you write to do that!