2017-03-04 86 views
6
from datetime import datetime, timedelta 
current_time = datetime.now().time() 
new_time = current_time - timedelta(seconds=10) 
>> TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.timedelta' 

如何從datetime.time對象中減去時間?這段代碼似乎只適用於datetime.datetime對象。從datetime.time減去時間對象

回答

2

在返回時間之前,您只需從當前的datetime對象中減去10秒即可。

current_time = (datetime.now() - timedelta(seconds=10)).time() 
2

Timedelta只對datetime.datetime和datetime.date對象有效。但是,你總是可以做

current_dt = datetime.datetime.now() 
newdt = currentdt - datetime.delta(seconds=10) 
new_time = newdt.time() 
1

日期時間減法後獲取時間:

from datetime import datetime, timedelta 
current_time = datetime.now() 
new_time = current_time - timedelta(seconds=10) 
new_time = new_time.time() 
print new_time 

輸出:10:56:43.408337