Jueun Kim
Jueun Kim

Reputation: 105

How to convert tuple type to int on python?

I'm Python beginner. I want to convert sqlcommand result (tuple type) into int 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 is tuple and I want to get int type from it.

Upvotes: 9

Views: 46728

Answers (2)

Eric
Eric

Reputation: 460

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]

Upvotes: 1

kindall
kindall

Reputation: 184191

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

Upvotes: 18

Related Questions