简体   繁体   中英

How can I format the datetime tuple returned by python from mysql

My python is running a query and returns the output txn_time as shown below.

    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= "SELECT txn_time FROM transactions WHERE CUSTOMERID in (12345) txn_type IN (111) ORDER BY 1 DESC"

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

I need to format it to the time: 2020-08-25 10:06:29 Tried to format is using strftime but couldn't achieve. Can someone help help or guide me to the right pages.

First, take the datetime object out of the tuple with this: txn_time = txn_time[0] . Then, simply use this: txn_time_str = txn_time.strftime("%Y-%m-%d %H:%M:%S") ! This should put the string you want into a variable called txn_time_str .

It's simple actually - in my case the result set returned a tuple so i just had to access the first element which had my result set. And then it automatically converted the time back to what was seen in the DB.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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