Home > Back-end >  how to divide a datetime object by an int
how to divide a datetime object by an int

Time:06-06

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?

CodePudding user response:

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

CodePudding user response:

What do you expect form dividing date by int?

time.timestamp()

returns number of seconds that have elapsed since January 1, 1970. Maybe datetime.timedelta will help you?

  • Related