如何格式化python从mysql返回的datetime元组

如何格式化python从mysql返回的datetime元组,python,datetime,datetime-format,pymysql,Python,Datetime,Datetime Format,Pymysql,我的python正在运行一个查询并返回输出txn_时间,如下所示 try: connection = pymysql.connect(host=db, user=user, password=pwd, db=db_name) with connection.cursor() as cursor: cursor.execute(

我的python正在运行一个查询并返回输出txn_时间,如下所示

    try:
    connection = pymysql.connect(host=db, user=user,
                                 password=pwd,
                                 db=db_name)
    with connection.cursor() as cursor:
        cursor.execute(**txn_query**.format(a,b,c))
        return cursor.fetchall()
except:
txn_query=“从(12345)txn_中的CUSTOMERID按1描述键入(111)订单的事务中选择txn_时间”

输出: (datetime.datetime(2020,8,25,10,6,29),)

我需要将其格式化为时间:2020-08-25 10:06:29
试图格式化正在使用strftime,但无法实现。是否有人可以帮助或指导我找到正确的页面。

首先,使用以下命令从元组中取出datetime对象:
txn\u time=txn\u time[0]
。然后,只需使用以下命令:
txn\u time\u str=txn\u time.strftime(“%Y-%m-%d%H:%m:%S”)
!这将把您想要的字符串放入一个名为
txn\u time\u str

的变量中,实际上很简单-在我的例子中,结果集返回了一个元组,所以我只需访问包含结果集的第一个元素。然后,它会自动将时间转换回数据库中显示的时间

#before
print(result)
(datetime.datetime(2020, 8, 25, 10, 6, 29),)


#after
result = result[0] #first element of the returned tuple
print(result)
2020-08-26 02:01:01

这回答了你的问题吗@manveti:OP获得的输出是datetime对象,而不是unix时间戳。可以通过
.isoformat(“”)
简单地格式化为字符串。这是否回答了您的问题?这很好,txn_time=txn_time[0]但是txn_time对我不起作用,无论如何,谢谢