简体   繁体   中英

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

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"

Alternatively you could do something like this

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

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM