Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 588
Akhil Mathew Avatar asked Jan 06 '23 06:01

Akhil Mathew


2 Answers

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()
like image 58
justhalf Avatar answered Jan 08 '23 19:01

justhalf


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.

like image 20
Mureinik Avatar answered Jan 08 '23 19:01

Mureinik