我的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=";从交易中选择txn_time,其中CUSTOMERID in(12345(txn_type in(111(ORDER BY 1 DESC";
输出:(datetime.datetime(2020,8,25,10,6,29(,(
我需要将其格式化为时间:2020-08-25 10:06:29尝试格式化正在使用strftime,但无法实现。有人能帮助我或引导我到正确的页面吗。
实际上很简单——在我的例子中,结果集返回了一个元组,所以我只需要访问具有结果集的第一个元素。然后它自动将时间转换回数据库中显示的时间。
#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
首先,将datetime对象从元组中取出,如下所示:txn_time = txn_time[0]
。然后,简单地使用这个:txn_time_str = txn_time.strftime("%Y-%m-%d %H:%M:%S")
!这应该将您想要的字符串放入一个名为txn_time_str
的变量中。