skip to Main Content

When I run this following select query on the command line in Mysql:

SELECT date_sent FROM books;

I get this sort of result (eg) | 2024-10-06 |

but if I run the same select query from inside python:

   # Select query 
    cur.execute("SELECT date_sent FROM books") 
    output = cur.fetchall() 
    for i in output: 
        print(i)

I get this as a result (eg) (datetime.date(2024, 10, 6),)

I don’t understand what object this has returned, and how I can use it as a date. I have tried splitting it like a text field, printing it as a list item, a tuple item or a dictionary item, but it seems untranslatable.

2

Answers


  1. You are being returned a datetime.date instance, which can be formatted as a string using method strftime.

        cur.execute("SELECT date_sent FROM books") 
        rows = cur.fetchall() 
        for row in rows:
            the_date = row[0]  # or row['date_sent'] if row is a dictionary
            print(the_date.strftime('%m/%d/%Y'))  # for example, 10/06/2024
    
    Login or Signup to reply.
  2. When you execute the query inside Python using cur.fetchall() it returns datetime.date object. If you want it to be formatted as string you can use strftime. In below example I have formatted as ‘%Y-%m-%d’

    Output will be ‘2024-10-06’

    cur.execute("SELECT date_sent FROM books") 
        output = cur.fetchall() 
    
    for i in output:
        date_sent = i[0]  
        formatted_date = date_sent.strftime('%Y-%m-%d') 
        print(formatted_date) 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search