如何格式化mysql从python返回的日期时间元组

问题描述

我的python正在运行查询,并返回输出txn_time,如下所示。

    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_type IN(111)ORDER BY 1 DESC中从客户标识中选择事务的txn_time”

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

我需要将其格式化为以下时间:2020-08-25 10:06:29 尝试使用strftime格式化但无法实现。有人可以帮忙还是可以引导我进入正确的页面

解决方法

首先,使用以下命令将日期时间对象从元组中取出:txn_time = txn_time[0]。然后,只需使用以下命令:txn_time_str = txn_time.strftime("%Y-%m-%d %H:%M:%S")!这应该将所需的字符串放入名为txn_time_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