1

I want to change tuple type data into int type during forloop. How to read those tuple data? (Because I want to convert those data into datetime )

>>> print data
((1424794931452.0,), (1424794931645.0,), (1424794931821.0,),(1424794932014.0,), (1424794932189.0,))

I have 5 tuple data(unixtime) and this is what I want to do.

for i in data:
    con = int(data[i][0])
    dt = datetime.fromtimestamp(con // 1000)
    s = dt.strftime('%Y-%m-%d %H:%M:%S')
    print(s)

I think those tuple data is ([0][0],[1][0],[2][0],[3][0],[4][0]) right?

What is problem? I don't know python well.

Jueun Kim
  • 105
  • 1
  • 2
  • 6
  • Check out the answer given by @AndrewClark [to this question](http://stackoverflow.com/questions/13260863/convert-a-unixtime-to-a-datetime-object-and-back-again-pair-of-time-conversion) for problems that fromtimestamp can cause (others have already answered your use of i problem) – LinkBerest Mar 28 '15 at 03:38

4 Answers4

2

You have a tuple containing single element tuples. You probably want something like:

from datetime import datetime

data = ((1424794931452.0,), (1424794931645.0,), (1424794931821.0,),(1424794932014.0,), (1424794932189.0,))

for elem in data:
    con = int(elem[0])
    dt = datetime.fromtimestamp(con // 1000)
    s = dt.strftime('%Y-%m-%d %H:%M:%S')
    print(s)

Output:

2015-02-24 11:22:11
2015-02-24 11:22:11
2015-02-24 11:22:11
2015-02-24 11:22:12
2015-02-24 11:22:12
jedwards
  • 29,432
  • 3
  • 65
  • 92
1

I think the problem is that i is the element in data, not an index. So you should do:

for i in data:
    con = int(i[0])
    dt = datetime.fromtimestamp(con // 1000)
    s = dt.strftime('%Y-%m-%d %H:%M:%S')
    print(s)
brunodea
  • 220
  • 1
  • 10
0

i is already a sub-tuple, not an index in data. So its enough to do:

from datetime import datetime

data = ((1424794931452.0,), (1424794931645.0,), (1424794931821.0,),(1424794932014.0,), (1424794932189.0,))

for i in data:
    dt = datetime.fromtimestamp(i[0] // 1000)
    s = dt.strftime('%Y-%m-%d %H:%M:%S')
    print(s)    

Result is:

2015-02-25 00:22:11
2015-02-25 00:22:11
2015-02-25 00:22:11
2015-02-25 00:22:12
2015-02-25 00:22:12
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

When you do for x in y syntax, x gets assigned to the elements of sequence on every iteration. To enumerate over the indexes, you would have to use the built-in function enumerate which returns both the indexes and the items.

I would do something like this instead:

for con in (int(d[0]) for d in data):
    do_something_with(con)
Shashank
  • 13,713
  • 5
  • 37
  • 63