How do I get just the hours, minutes, and seconds, but separately?

Question:

print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))

time1 = datetime.time(time1h,time1m,time1s)
time2 = datetime.time(time2h,time2m,time2s)

diff = datetime.timedelta(hours=(time2.hour - time1.hour), minutes=(time2.minute - time1.minute), seconds=(time2.second - time1.second))
print(diff)

I am trying to print the results from the diff variable separately from each other so I can format it like
"You ran for (diffhours) hours, (diffminutes) minutes, and (diffseconds) seconds"

Asked By: Mahdi

||

Answers:

Alternatively you could do something like this

output_string = str(diff).split(':')
print("You ran for {} hours, {} minutes, and {} seconds".format(*output_string))
Answered By: luk_dsp

While you can use diff.seconds and then carry out various calculations to convert it to hours and minutes as suggested in the other answers, it’s also possible to convert diff to a string and process it that way:

diff = str(diff).split(':') # diff will be something like 1:01:23
print(f'You ran for {diff[0]} hours, {diff[1]} minutes and {diff[2]} seconds')

Example output:

You ran for 1 hours, 01 minutes and 01 seconds
Answered By: PangolinPaws
from datetime import datetime, timedelta 
time1 = input("Enter your start time:")
time1 = datetime.strptime(time1, "%H:%M:%S")
time2 = input("Enter your end time:")
time2 = datetime.strptime(time2, "%H:%M:%S")

diff = (time2-time1)
print(diff)

============ output ================

Enter your start time:1:20:00
Enter your end time:6:20:00
5:00:00

Here is the code:

print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))

time1 = timedelta(hours=time1h, minutes=time1m, seconds=time1s)
time2 = timedelta(hours=time2h, minutes=time2m, seconds=time2s)
diff = time2-time1

total_sec = diff.total_seconds()
h = int(total_sec // 3600)
total_sec = total_sec % 3600
m = int(total_sec // 60)
s = int(total_sec % 60)

print(f"You ran for {h} hours, {m} minutes, and {s} seconds")
Answered By: CYBER HK
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.