Subtract hours and minutes from time


Python Problem Overview

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


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.

Python Solutions

Solution 1 - Python

from datetime import datetime, timedelta

d = - timedelta(hours=0, minutes=50)

d.strftime('%H:%M %p')

Solution 2 - Python

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

Solution 3 - Python

from datetime import datetime

d1 = datetime.strptime("01:05:00.000", "%H:%M:%S.%f")
d2 = datetime.strptime("00:50:00.000", "%H:%M:%S.%f")

print (d1-d2)


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachhyaView Question on Stackoverflow
Solution 1 - PythonasfartoView Answer on Stackoverflow
Solution 2 - PythonTaniyaView Answer on Stackoverflow
Solution 3 - PythonFuzed MassView Answer on Stackoverflow