Richard
Richard

Reputation: 15862

How to retrieve a time stamp with the right formatting from a sql database using python

I want to retrieve a time stamp from a sql database with proper formatting. This is the partial code I am using:

import MySQLdb

def connectDB(self):
    global cursor
    DATABASE = MySQLdb.connect(
        host    = self.HOST,
        user    = self.USER,
        passwd  = self.PASS,
        db      = self.DB,
        port    = self.PORT,
        ssl = self.SSL_SETTINGS
        )

    cursor = DATABASE.cursor()

def getLastReport(self):
    sql = "SELECT timestamp FROM dataset Limit 0,1;"
    self.connectDB()
    cursor.execute(sql)
    lastReport = cursor.fetchone()
    return lastReport

and last report returns:

(datetime.datetime(2010, 7, 7, 19, 55),)

I want something like this:

2010-7-7 19:55

I know how to change this to a string and then reformat it but there should be an easy way to grab the time stamp so that it is already formatted. also how would one grab a float or int or string so that it is already formatted rather then trying to format it yourself. I am new to sql but there must be a way to grab data formatted correctly seeing that you have to declare the data types when creating the tables.

Upvotes: 1

Views: 190

Answers (1)

unutbu
unutbu

Reputation: 879681

You could use the DATE_FORMAT mysql function, though this is no easier than doing it on the Python side. In fact, it is much more limited, because fetchone returns a Python string instead of a datetime object.

sql = "SELECT DATE_FORMAT(timestamp,"%Y-%m-%d %k:%i") FROM dataset Limit 0,1;"

compared to

adate=datetime.datetime(2010, 7, 7, 19, 55)
adate.strftime('%Y-%m-%d %H:%M')
# 2010-07-07 19:55

Upvotes: 3

Related Questions