I can’t seem to divide a datetime.time
object by an int
.
Looking at the documentation I can’t figure out why it isn’t working.
I get the error: unsupported operand type(s) for /: 'datetime.time' and 'int'
.
JavaScript
x
9
1
import datetime
2
from datetime import datetime, timedelta, timezone, date
3
4
time = datetime.strptime("04:23:40", "%H:%M:%S")
5
print(time)
6
print(time.time())
7
time_div = time.time() / 2
8
print(time_div)>
9
I did see a method that splits the time down into second then performs the division on the number of seconds, but wondering if there is a better way?
Advertisement
Answer
I think you are confusing a (non-existing) datetime.datetime
method with a datetime.timedelta
method (see timedelta). Timedeltas can be divided. E.g.:
JavaScript
1
7
1
from datetime import datetime, timedelta
2
3
t = datetime.strptime("04:23:40", "%H:%M:%S")
4
d = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
5
6
print(d/2) # Output: '2:11:50' (type: 'datetime.timedelta')
7