Reputation: 78
In my basketball sim, the quarter clock is set to a 3 digit number, 12 minute quarters * 60 seconds = 720 seconds. After the result of my play, I subtract a random number, in-between 10-24, from the quarter clock. I print the result of my play, as well as the quarter clock. Example code:
quarter_clock = 12 * 60
time_runoff = random.randint(10,24)
def play():
if player_makes_shot:
print("player makes the shot")
quarter_clock = quarter_clock - time_runoff
print(quarter_clock)
output:
player makes shot
702
How can I make the clock output to be in a minute-second format like this:
11:42
Thanks for the help! :)
Upvotes: 0
Views: 422
Reputation: 28620
I'd use the time
library here. It's made to do precisely this, and you can put into any format you'd like:
So for minutes and seconds (Ie 12:00
), do time.strftime("%M:%S", time.gmtime(quarter_clock))
time.strftime("%M:%S", time.gmtime(702))
Out[13]: '11:42'
And it's just a simple change in the print statement
import time
import random
quarter_clock = 12 * 60
time_runoff = random.randint(10,24)
def play():
if player_makes_shot:
print("player makes the shot")
quarter_clock = quarter_clock - time_runoff
print(time.strftime("%M:%S", time.gmtime(quarter_clock)) )
Upvotes: 1
Reputation: 4761
You can use divmod
, which "returns the quotient and remainder after a division of two numbers":
>>> divmod(702,60)
(11, 42)
So you can do something like this:
>>> minutes, seconds = divmod(702,60)
>>> print(f"{minutes}:{seconds}")
11:42
EDIT:
You can also add a 0 to the left of the seconds in case it is a 1-digit number, e.g.:
>>> minutes, seconds = divmod(662,60)
>>> print(f"{minutes}:{seconds:02d}")
11:02
Upvotes: 2
Reputation: 4243
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return hour,minutes,seconds
def get_sec(h,m,s):
"""Get Seconds from time."""
if h==np.empty:
h=0
if m==np.empty:
m=0
if s==np.empty:
s=0
return int(h) * 3600 + int(m) * 60 + int(s)
Upvotes: 0