Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract hours and minutes from time

In my task what I need to do is to subtract some hours and minutes like (0:20,1:10...any value) from time (2:34 PM) and on the output side I need to display the time after subtraction. time and hh:mm value are hardcoded

Ex:

my_time = 1:05 AM  duration = 0:50 

so output should be 12:15 PM

Output should be exact and in AM/PM Format and Applicable for all values (0:00 < Duration > 6:00) .

I don't care about seconds, I only need the hours and minutes.

like image 321
Sachhya Avatar asked Sep 25 '17 09:09

Sachhya


People also ask

How do I subtract hours and minutes?

To subtract time, subtract the minutes then subtract the hours. Since we can't have negative minutes, add 60 to the minutes and subtract 1 from the hours (60 minutes = 1 hour).

How do you calculate time in hours and minutes?

The formula for calculating elapsed time is elapsed time = end time – start time. Subtract the minutes and hours separately. For example to calculate the elapsed time between 12:10 and 16:40, subtract 12:10 from 16:4. Looking at the hours, 16 – 12 = 4 and looking at the minutes, 40 – 10 = 30.


2 Answers

from datetime import datetime, timedelta  d = datetime.today() - timedelta(hours=0, minutes=50)  d.strftime('%H:%M %p') 
like image 138
asfarto Avatar answered Sep 19 '22 18:09

asfarto


This worked for me :

from datetime import datetime s1 = '10:04:00' s2 = '11:03:11' # for example format = '%H:%M:%S' time = datetime.strptime(s2, format) - datetime.strptime(s1, format) print time 
like image 45
Taniya Avatar answered Sep 17 '22 18:09

Taniya