AKHIL MATHEW AKHIL MATHEW - 7 months ago 17
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

total_seconds=diff.seconds
time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
if(e<s):
self.units = 0
else:
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?

Answer

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:

total_seconds=diff.total_seconds()
Comments