1

I have code that selects the max timestamp from a MySQL db as follows:

cursor = connection.cursor()
cursor.execute("SELECT max(played_at) FROM 
testDB.Log;")
max_date = cursor.fetchall()

it returns a datetime.datetime object like this:

((datetime.datetime(2019, 6, 4, 11, 44, 5),),)

I need it to return a timestamp in the format %Y-%m-%d %H:%M:%S

I have tried using strptime(), datetime(), and strftime() but each time I get the error "tuple has no object (insert one of the three)"

How can I get the format i want?

1
  • strftime is just fine, the only problem is that you need to apply it to an index of the tuple, not the whole tuple itself. max_date[0][0] gets you at the datetime itself Commented Jun 13, 2019 at 11:38

1 Answer 1

3

The cursor is returning the database row as a tuple, you need to access individual columns values using square bracket notation. Columns are indexed from 0.

example:

print(max_date[0].strftime('%Y-%m-%d %H:%M:%S'))

Additionally cursor.fetchall() returns a list of tuples. You could use cursor.fetchone() in this particular instance given select(max) would always return one row.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.