Skip to content
Advertisement

how to divide a datetime object by an int

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'.

import datetime
from datetime import datetime, timedelta, timezone, date

time = datetime.strptime("04:23:40", "%H:%M:%S")
print(time)
print(time.time())
time_div = time.time() / 2
print(time_div)>

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.:

from datetime import datetime, timedelta

t = datetime.strptime("04:23:40", "%H:%M:%S")
d = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)

print(d/2) # Output: '2:11:50' (type: 'datetime.timedelta')
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement