Reputation: 81
I've written some code in python 2.7 for a timer program. The downside is that the result is in seconds and I need it in Minutes:Seconds
. I've tried to format the time to no avail. Can anyone help?"
from Tkinter import *
import time
root = Tk()
root.title("Timer")
canvas = Canvas(root)
canvas.pack()
time=1
def tick():
canvas.delete(ALL)
global time
time += 10
if time >= 120:
canvas.create_text(180,140, font = ("Calibri",200),text=time,fill='red')
else:
canvas.create_text(180,140, font = ("Calibri",200),text=time,fill='green')
if time == 1000:
time = 0
tick()
else:
canvas.after(1000, tick)
def reset():
global time
time = 0
def close_window():
root.destroy()
b = Button(root,text="Reset", command=reset)
c = Button(root,text="Quit", command=close_window)
b.pack(side = LEFT)
c.pack(side = RIGHT)
canvas.after(1, tick)
root.mainloop()
Upvotes: 8
Views: 12813
Reputation: 23068
You can use datetime.timedelta
import datetime
number_of_seconds = 1000
str(datetime.timedelta(seconds=number_of_seconds))
# output
'0:16:40'
Or even better since you only want mm:ss
, you can use time.strftime
import time
number_of_seconds = 1000
time.strftime("%M:%S", time.gmtime(number_of_seconds))
# output
'16:40'
Documentations are available for datetime module and for time module.
Upvotes: 13
Reputation: 881605
Being a somewhat-lazy programmer, I like to reuse good work that's embodied in the standard library (where it might well get optimized and is surely very well tested). So...:
import datetime
def secs_to_MS(secs):
return datetime.datetime.fromtimestamp(secs).strftime('%M:%S')
If you need to have hours there as well, that's easy too:
import datetime
def secs_to_HMS(secs):
if secs < 3600:
return datetime.datetime.fromtimestamp(secs).strftime('%M:%S')
else:
return datetime.datetime.fromtimestamp(secs).strftime('%H:%M:%S')
Upvotes: 5
Reputation:
To convert seconds into minutes and seconds, you can use the divmod
function:
>>> time = 1000 # 1000 seconds
>>> divmod(1000, 60)
(16, 40)
>>>
The first number in the outputed tuple is the minutes and the second is the remaining seconds. You can then use str.format
to make this tuple into the string you want:
>>> time = 1000
>>> '{}:{}'.format(*divmod(time, 60))
'16:40'
>>>
Upvotes: 6