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()
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With