Subtracting time from a datetime.time object

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' 

How can I subtract time from a datetime.time object? This code only works with datetime.datetime objects.

+6
source share
3 answers

You can simply subtract 10 seconds from the current datetime object before returning the time.

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

Timedelta only works with datetime.datetime and datetime.date objects. But you can always do

 current_dt = datetime.datetime.now() newdt = currentdt - datetime.delta(seconds=10) new_time = newdt.time() 
+2
source

Get the time after subtracting by time:

 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

+1
source

Source: https://habr.com/ru/post/1015468/


All Articles