AKHIL MATHEW AKHIL MATHEW - 6 months ago 10x
Python Question

When I substract two datetime object in python it is considering only time not taking day

I have two date time objects

`statrt_time` and `end_time`

my code is

if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s

time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
self.units = 0
self.units = math.ceil(no_of_units)

Here when I subtract time within the same day it is giving the correct difference. But when the day is changed, it is not calculating the day difference but only giving time difference. How can I add day difference also?


Use total_seconds() instead of seconds.

timedelta.seconds just shows "second" part of the difference, while total_seconds() shows the duration of the difference in seconds. See Mureinik's answer for more details.

So, use this: