-1

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.

Subodh
  • 61
  • 1
  • 10
  • Does this answer your question? [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – manveti Sep 09 '20 at 00:08
  • @manveti: the output that the OP gets is a datetime object, not unix timestamp. Could simply format to string by `.isoformat(' ')`. – FObersteiner Sep 09 '20 at 05:50
  • Does this answer your question? [ISO time (ISO 8601) in Python](https://stackoverflow.com/questions/2150739/iso-time-iso-8601-in-python) – FObersteiner Sep 09 '20 at 05:51

2 Answers2

1

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
Subodh
  • 61
  • 1
  • 10
0

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.

Seth
  • 2,214
  • 1
  • 7
  • 21
  • this was fine, txn_time = txn_time[0] but that txn_time_str didn't work for me, thanks anyway – Subodh Sep 09 '20 at 15:00