Python - MySQL fetching values

Chris Rebert clp2 at rebertia.com
Thu May 6 05:12:50 EDT 2010


On Thu, May 6, 2010 at 1:47 AM, Kurian Thayil <kurianmthayil at gmail.com> wrote:
<snip>
> the expected output is 05:35:05.
>
> Now, here is code snippet,
>
>                 cursor1=getconnect1.cursor()
>                 getrows=cursor1.execute("""SELECT
> TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info
> WHERE info_ctrlid=%s""", (retryinterval,controlid1,))
>                 rawstatus20result=cursor1.fetchone()
>                 print "Raw result is",rawstatus20result
>                 status20result=rawstatus20result[0]
>                 print "The query result for Status
> 20:",status20result,";Time now is",timeformat
>
> The output is:
>
> Raw result is (datetime.timedelta(0, 20105),)
> The query result for Status 20: 5:35:05 ;Time now is 05:22:00
> Match not found.
> New call to be made
> Getting next value if any...
>
> If you look closer, the time fetched by python module was 5:35:05 instead of
> 05:35:05. How can I get this time format? Thanks in advance.

You're getting back a time delta (i.e. quantity/duration of time, e.g.
"3 hours") rather than an actual time (i.e. temporal coordinates for a
particular instant of time, e.g. "5:15PM and 2 seconds"), and
timedelta defines its stringification differently, hence your issue. I
would guess that getting back a timedelta instead of a time is some
quirk of MySQLdb; haven't used it though, so I'm just guessing.

Anyway, you can work around this by converting the timedelta object to
a time object yourself:
#Untested Code!
from datetime import time
minutes, seconds = divmod(status20result.seconds, 60)
hours, minutes = divmod(minutes, 60)
time_result = time(hours, minutes, seconds, status20result.microseconds)
print "The query result for Status 20:",time_result,";Time now is",timeformat

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list