tags:

views:

69

answers:

4

Hello all, I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time.

def getLastReport(self, sql):



    self.connectDB()
    cursor.execute(sql)
    lastReport = cursor.fetchall()

    date = lastReport[0][0].strftime('%Y-%m-%d %H:%M UTC')

    dataset_id = int(lastReport[0][1])

    cursor.close()
    DATABASE.close()
    return date, dataset_id  
+3  A: 

Have you looked at the datetime module? http://docs.python.org/library/datetime.html

Convert your SQL time into a datetime, and make a timedelta object of 2.5 hours. Then add the two.

from datetime import datetime

dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )
dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 )
robert
I can't seem to get your code to work. error: Traceback (most recent call last): File "<pyshell#24>", line 1, in -toplevel- dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )AttributeError: 'module' object has no attribute 'strptime'
Richard
Either change your import to `from datetime import datetime` or change the code to `datetime.datetime.strptime`
AdmiralNemo
A: 

Add datetime.timedelta(0, 2.5*60*60).

Ignacio Vazquez-Abrams
2*60*60 + 30*60 would be better as it doesn't return a float. But the most it could be off is a second.
robert
A: 

Try this (switch sqlite3 with whatever db interface you are using):

f= lastReport[0][0]
newtime = sqlite3.Time(f.hour + 2, f.minute + 30, f.second, f.microsecond)

I thought that adding datetime.timedelta(0, 2.5*60*60) like Igancio suggests would be the best solution, but I get:

'unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'.
orangeoctopus
A: 

I usually use the 3rd party module, dateutil, for this sort of thing. It makes this sort of time-shifting much easier to do and understand:

http://labix.org/python-dateutil

Mike Driscoll