2010-07-21 34 views
0

我需要能夠將我從sql數據庫接收到的時間對象上的時間轉換爲python。這裏是我正在使用的當前Python代碼,沒有任何轉換。我需要增加2個半小時的時間。在Python中添加2個半小時到時間對象

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

你看過日期時間模塊嗎? http://docs.python.org/library/datetime.html

將您的SQL時間轉換爲日期時間,並使2.5小時的timedelta對象。然後添加這兩個。

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) 
+1

我似乎無法讓你的代碼工作。錯誤:回溯(最近一次調用最後一次): 文件「」,第1行,在-toplevel- dt = datetime.strptime(date,'%Y-%m-%d%H:%M') AttributeError :'模塊'對象沒有屬性'strptime' – Richard 2010-07-21 12:28:56

+1

或者將你的導入改爲'from datetime import datetime'或者將代碼改爲'datetime.datetime.strptime' – AdmiralNemo 2010-07-21 12:44:45

1

添加datetime.timedelta(0, 2.5*60*60)

+1

2 * 60 * 60 + 30 * 60會更好不返回一個浮點數。但最多的可能是關閉了一秒鐘。 – robert 2010-07-21 12:06:18

1

試試這個(與任何DB接口使用的是開關的sqlite3):

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

我認爲像Igancio加入datetime.timedelta(0,2.5 * 60 * 60)建議將是最好的解決辦法,但我得到:

'unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'. 
相關問題