python time arithmetic with datetime?

Status
You're currently viewing only gloucester's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

gloucester

Ars Scholae Palatinae
996
You've noticed that datetime.time objects do not support arithmetic, but both datetime.time and datetime.timedelta objects do. You can use combinations of them to do what you want.

If you care only about quantities of time, use only datetime.timedelta objects:
Code:
dt1 = datetime.timedelta(seconds=1)
dt2 = datetime.timedelta(seconds=2)
dt3 = dt1 + dt2  # result is datetime.timedelta(3)
If you want to do time-of-day arthithmetic, the easiest thing to do is start with a datetime.datetime object with dummy values of year, month, and day, and add datetime.timedelta objects to it:
Code:
t = datetime.datetime(year=1, month=1, day=1, hour=12, minute=30, second=30)
dt = datetime.timedelta(hours=12)
t2 = t + dt # result is datetime.datetime(1, 1, 2, 0, 30, 30)
Then use the time() method to get a datetime.time object if needed:
Code:
t3 = t2.time() #result is datetime.time(0, 30, 30)
 
Status
You're currently viewing only gloucester's posts. Click here to go back to viewing the entire thread.
Not open for further replies.