Home > Net >  Subtracting time in python where the result is always positive
Subtracting time in python where the result is always positive

Time:06-29

I am trying to compute differences in time as follows:

import datetime

time_1 = datetime.datetime.strptime('18:00',"%H:%M")
time_2 = datetime.datetime.strptime('05:00',"%H:%M")

time_interval = time_2 - time_1

This results in:

datetime.timedelta(days=-1, seconds=39600)

Now, when I add this to some date like:

low_date = datetime.datetime(2000, 1, 1, 18, 0)
low_date   time_interval

This results in:

datetime.datetime(2000, 1, 1, 4, 0)

So, it is representing going backwards in time but I always want the difference to go forward i.e. time_2 should be interpreted as being in the future of time_1. In this case, time_2 is 5 AM the next day.

If time_2 was something like:

time_2 = datetime.datetime.strptime('21:00',"%H:%M")

It should be interpreted as 9 PM on the same day.

EDIT

Solved it by adding something like:

if time_interval.days < 0:
    time_interval = datetime.timedelta(
         days=0,
         seconds=time_interval.seconds)

CodePudding user response:

Both times you give are in the same day.

If you mean the second one to always be in the future (positive difference), you need to move it into the future, if it's not already. Check it for being "smaller", and if it's smaller, you have to add a day to it.

time_1 = datetime.datetime.strptime('18:00',"%H:%M")
time_2 = datetime.datetime.strptime('05:00',"%H:%M")

if time_2 < time_1:
    time_2  = datetime.timedelta(days=1)

time_interval = time_2 - time_1
# datetime.timedelta(seconds=39600)
# that's 6 5 = 11 hours = 39600 seconds

CodePudding user response:

You need to subtract time_2 from time_1, otherwise you will end with negative and nonsense values:

import datetime

time_1 = datetime.datetime.strptime('18:00',"%H:%M")
time_2 = datetime.datetime.strptime('05:00',"%H:%M")

if time_1 <= time_2:
    time_1, time_2 = time_2, time_1
    
time_interval = time_1 - time_2
print(time_interval)

Output:

13:00:00
  • Related