Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
Jueun Kim Avatar asked Mar 27 '15 23:03

Jueun Kim


People also ask

How do you convert a tuple element to an integer?

Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform the conversion using tuple() and int(). Extraction of elements is done by replace() and split().

How do you convert a tuple in Python?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

How do you convert to int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you turn a tuple into a variable?

Example: Adding Variables to a Tuple using vars() Function tuple() is used to convert and store the 'n' number of variables in a tuple type. This method is used in complicated cases.


2 Answers

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])
like image 137
kindall Avatar answered Sep 23 '22 17:09

kindall


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]
like image 40
Eric Avatar answered Sep 20 '22 17:09

Eric