简体   繁体   English

Python pymysql datetime.datetime元组到时间戳

[英]Python pymysql datetime.datetime tuple to timestamp

I have code that selects the max timestamp from a MySQL db as follows: 我有从MySQL数据库中选择最大时间戳的代码,如下所示:

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对象,如下所示:

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

I need it to return a timestamp in the format %Y-%m-%d %H:%M:%S 我需要它以%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)" 我尝试使用strptime(),datetime()和strftime(),但是每次出现错误“元组没有对象(插入三个对象之一)”时,

How can I get the format i want? 如何获得我想要的格式?

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. 列从0开始索引。

example: 例:

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

Additionally cursor.fetchall() returns a list of tuples. 另外,cursor.fetchall()返回元组列表。 You could use cursor.fetchone() in this particular instance given select(max) would always return one row. 您可以在此特定实例中使用cursor.fetchone(),因为select(max)将始终返回一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM