When I subtract two datetime objects in python, it only considers time not taking a day

I have two time objects

`statrt_time` and `end_time`

my code

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 the time on the same day, it gives the correct difference. But when the day changes, it does not calculate the difference in the day, but only gives the difference in time. How can I add the difference per day?

+4
source share
3 answers

Use total_seconds()instead seconds.

timedelta.secondsjust shows the "second" part of the difference, but total_seconds()shows the duration of the difference in seconds. See Mureinik for more details .

So use this:

total_seconds=diff.total_seconds()
+6
source

total_seconds - timedelta , , - days, seconds miliseconds. seconds . total_seconds() , , .

+3

I have another way to do it. BUT WORK AROUND ..

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
    days=diff.days// convert difference to day instead of seconds//
    days_seconds=0
    if(days>0): //Checking whether the difference exceeds a day//
        days_seconds=days*24*3600 //If so convert it to seconds//

    total_seconds=diff.seconds+days_seconds
    time_diff = (total_seconds/3600.0)
0
source

All Articles