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?
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()
total_seconds
is a timedelta
object which stores the difference between two datetimes using three fields - days
, seconds
and miliseconds
. Your snippet just uses the seconds
attributes instead of the entire difference. The total_seconds()
method takes care of this for you and returns, well, the total number of seconds between two datatimes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With