Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract two times in python

People also ask

How do I get the difference between two times in Python?

To get the difference between two-time, subtract time1 from time2. A result is a timedelta object. The timedelta represents a duration which is the difference between two-time to the microsecond resolution. To get a time difference in seconds, use the timedelta.

How do you subtract 2 numbers in Python?

To subtract the numbers, I have used sub=a-b. The function is returned as return sub. To get the output, I have used print(“Result is: “,subtraction(number1,number2)).


Try this:

from datetime import datetime, date

datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)

combine builds a datetime, that can be subtracted.


Use:

from datetime import datetime, date

duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)

Using date.min is a bit more concise and works even at midnight.

This might not be the case with date.today() that might return unexpected results if the first call happens at 23:59:59 and the next one at 00:00:00.


instead of using time try timedelta:

from datetime import timedelta

t1 = timedelta(hours=7, minutes=36)
t2 = timedelta(hours=11, minutes=32)
t3 = timedelta(hours=13, minutes=7)
t4 = timedelta(hours=21, minutes=0)

arrival = t2 - t1
lunch = (t3 - t2 - timedelta(hours=1))
departure = t4 - t3

print(arrival, lunch, departure)

The python timedelta library should do what you need. A timedelta is returned when you subtract two datetime instances.

import datetime
dt_started = datetime.datetime.utcnow()

# do some stuff

dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())