I wrote a program that's suppose to run for hours to do its job, The program has many functions defined and also it functions aren't in order, the user only sees the timer only when the program goes into the function that's for displaying and then the time freezes because of the other functions, is there a way to display the time all throughout the program without freezing, the timer also doesn't make it to 60 it goes to 34 and then changes the minutes
change my code below
#!/usr/bin/env python 2.7.11
import timeit,os
Start = timeit.default_timer()
def Func1():
pass #This Function has things in it I just put pass to show
def Func2():
pass
def Func3():
End = timeit.default_timer()-Start
Hours = int(round((End/60**2)))
Mins = int(round(End/60))
Secs = int(round(End))
if Secs >= 60 and Mins < 60:
Mins+=1;
if Secs > 60:
Secs=int(round(Secs-60))
else:
Secs=0
if Mins >= 60 and Secs >= 60:
Hours+=1
Mins=0;
if Secs > 60:
Secs=int(round(Secs-60));
else:
Secs=0
if Hours > 9 and Mins > 9 and Secs > 9:
Timed = ' Time: %d:%d:%d ' %(Hours,Mins,Secs)
#
if Hours > 9 and Mins > 9 and Secs <= 9:
Timed = ' Time: %d:%d:0%d ' %(Hours,Mins,Secs)
if Hours > 9 and Mins <= 9 and Secs > 9:
Timed = ' Time: %d:0%d:%d ' %(Hours,Mins,Secs)
if Hours <= 9 and Mins > 9 and Secs > 9:
Timed = ' Time: 0%d:%d:%d ' %(Hours,Mins,Secs)
#
if Hours <= 9 and Mins > 9 and Secs > 9:
Timed = ' Time: %0d:%d:%d ' %(Hours,Mins,Secs)
if Hours > 9 and Mins <= 9 and Secs > 9:
Timed = ' Time: %d:0%d:%d ' %(Hours,Mins,Secs)
if Hours > 9 and Mins > 9 and Secs <= 9:
Timed = 'Time: %d:%d:0%d ' %(Hours,Mins,Secs)
#
if Hours > 9 and Mins <= 9 and Secs <= 9:
Timed = ' Time: %d:0%d:0%d ' %(Hours,Mins,Secs)
if Hours <= 9 and Mins <= 9 and Secs > 9:
Timed =' Time: 0%d:0%d:%d ' %(Hours,Mins,Secs)
#
if Hours <= 9 and Mins <= 9 and Secs > 9:
Timed = ' Time: 0%d:0%d:%d ' %(Hours,Mins,Secs)
if Hours <= 9 and Mins <= 9 and Secs <= 9:
Timed = ' Time: 0%d:0%d:0%d ' %(Hours,Mins,Secs)
os.system('clear');print Timed
if __name__=='__main__':
while True:
Func3()
Func1()
Func2()
It sounds like you have a couple of problems and it would be great if you could post all the relevant code. For the first problem that your timer resets, you could do something like this instead, where you always keep the start variable in memory and don't overwrite it, and then just ping for time_elapsed = end- start whenever you want the time elapsed(that way it won't get reset accidentally which sounds like what is happening to you).
import time
start = time.time()
print("hello")
end = time.time()
print(end - start)
Now you've stored start time in memory, you can always overwrite the end variable and get the updated time without worrying about the timer stopping and restarting.
Also for the second part of your problem regarding your Func3(), you could do something like this which does only a single division for quotient and remainder to be more efficient. This should give you the accurate time elapsed in HH:MM::SS.
time_elapsed = end - start
Mins, Secs = divmod(time_elapsed, 60)
Hours, Mins = divmod(Mins, 60)
print "%d:%02d:%02d" % (Hours, Mins, Secs)
Related
I've been working on a personal assistant in python for a long time now and I've come across a problem that I can't solve.
I want to add a reminder.
I want to combine the alarm code and assistant code in two different loops.
When I set the alarm timer I want to do the other input tasks until the timer runs out.
How can I do that? Thanks.
I've tried this code, but it doesn't work because I only have one loop:
import datetime
import os
import time
import random
def assistant():
command = input('command: ')
if command == '1':
print('is it one')
elif command == '2':
print('is it two')
elif command == 'alarm':
import datetime
def check_alarm_input(alarm_time):
if len(alarm_time) == 1: # [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len(alarm_time) == 2: # [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0:
return True
elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0 and \
alarm_time[2] < 60 and alarm_time[2] >= 0:
return True
return False
# Get user input for the alarm time
print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
while True:
alarm_input = input(">> ")
try:
alarm_time = [int(n) for n in alarm_input.split(":")]
if check_alarm_input(alarm_time):
break
else:
raise ValueError
except ValueError:
print("ERROR: Enter time in HH:MM or HH:MM:SS format")
# Convert the alarm time from [H:M] or [H:M:S] to seconds
seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
# Get the current time of day in seconds
now = datetime.datetime.now()
current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
# Calculate the number of seconds until alarm goes off
time_diff_seconds = alarm_seconds - current_time_seconds
# If time difference is negative, set alarm for next day
if time_diff_seconds < 0:
time_diff_seconds += 86400 # number of seconds in a day
# Display the amount of time until the alarm goes off
print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
# Sleep until the alarm goes off
time.sleep(time_diff_seconds)
# Time for the alarm to go off
print("Wake Up!")
while True:
assistant()
1.Reminder code:
import datetime
import os
import time
import random
def check_alarm_input(alarm_time):
"""Checks to see if the user has entered in a valid alarm time"""
if len(alarm_time) == 1: # [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len(alarm_time) == 2: # [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0:
return True
elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0 and \
alarm_time[2] < 60 and alarm_time[2] >= 0:
return True
return False
# Get user input for the alarm time
print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
while True:
alarm_input = input(">> ")
try:
alarm_time = [int(n) for n in alarm_input.split(":")]
if check_alarm_input(alarm_time):
break
else:
raise ValueError
except ValueError:
print("ERROR: Enter time in HH:MM or HH:MM:SS format")
# Convert the alarm time from [H:M] or [H:M:S] to seconds
seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
# Get the current time of day in seconds
now = datetime.datetime.now()
current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
# Calculate the number of seconds until alarm goes off
time_diff_seconds = alarm_seconds - current_time_seconds
# If time difference is negative, set alarm for next day
if time_diff_seconds < 0:
time_diff_seconds += 86400 # number of seconds in a day
# Display the amount of time until the alarm goes off
print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
# Sleep until the alarm goes off
time.sleep(time_diff_seconds)
# Time for the alarm to go off
print("Wake Up!")
2.Representative assistant code:
def assistant():
command = input('command: ')
if command == '1':
print('is it one')
elif command == '2':
print('is it two')
while True:
assistant()
I am planning such an output
command: 1
is it one
command: 2
is it two
command: alarm
Set a time for the alarm (Ex. 06:30 or 18:30:00)
>> 13:00
Alarm set to go off in 1:30:00
command: 1
is it one
command: 2
is it two
Wake Up!
command: 1
is it one
command: 2
is it two
class time:
def __init__(self,hrs,mins,secs):
self.hrs = hrs
self.mins= mins
self.secs = secs
def __str__(self):
return (str(self.hrs%24)+":"+str(self.mins)+":"+str(self.secs))
def __repr__(self):
return (str(self.hrs%24)+":"+str(self.mins)+":"+str(self.secs))
When I do input the time, like when I put t = time(0,0,90).
How do I get the code to return 0:1:30?
How would I do the below also too?
Add a method called increment. This should add one second to the current time. Make sure that you check all the boundary conditions. When the time is 23:59:59 is incremented, it should roll over to 00:00:00.
I'd go a totally different route. Presenting it here in case it helps you.
class Time:
def __init__(self, hh, mm, ss):
self.time = hh*3600 + mm*60 + ss # Total seconds
#property
def hours(self):
return (self.time % 86400) // 3600
#property
def mins(self):
return (self.time % 3600) // 60
#property
def secs(self):
return self.time % 60
def increment(self):
self.time += 1
This is, imo, the simplest and most straightforward way to do it. If you've got multiple values that have to stay in sync, my advice is not to store them separately: just store them together in the underlying system, and separate them out when the user wants them.
When I do input the time, like when I put t = time(0,0,90). How do I get the code to return 0:1:30?
This can be done by simply moving the seconds up to minutes and minutes up to hours, scaling as necessary. Start with:
hh = 0
mm = 0
ss = 90
and the code to do it is a relatively simple:
while ss >= 60:
ss -= 60
mm += 1
while mm >= 60:
mm -= 60
hh = (hh + 1) % 24
Note that's not the most efficient way to do it, especially if the value can be high. If that's a possibility, you're better off with something like:
mm += (ss // 60) ; ss = ss % 60
hh += (mm // 60) ; mm = mm % 60
hh = hh % 24
Add a method called increment. This should add one second to the current time. Make sure that you check all the boundary conditions. When the time is 23:59:59 is incremented, it should roll over to 00:00:00.
Following a similar pattern (and assuming you've already fixed it to ensure values are properly clamped), this is also relatively easy.
ss = (ss + 1) % 60 # add second, wrapping if needed.
if ss == 0: # if second wraps, do same to minute.
mm = (mm + 1) % 60
if mm == 0: # if minute wraps, increment hour.
hh = (hh + 1) % 24
Note that I haven't integrated that into your specific code, I'm more treating Python as a pseudo-code language (at which it excels). That's because it's classwork and you'll learn a lot more by doing it yourself (once you know how, of course).
You should take the algorithms I've provided and adapt them for your own code.
I recommend you make a method to add an hour min and sec and the increment method just calls the add sec method. In the methods they handle when they reach their respective limits.
class time:
def __init__(self,hrs,mins,secs):
self.secs = secs % 60
self.mins = (mins + (secs // 60)) % 60
self.hrs = (hrs + (mins // 60)) % 24
def add_hour(self):
if self.hrs == 23:
self.hrs = 0
else:
self.hrs += 1
def add_min(self):
if self.mins == 59:
self.add_hour()
self.mins = 0
else:
self.mins += 1
def add_sec(self):
if self.secs == 59:
self.add_min()
self.secs = 0
else:
self.secs += 1
def increment(self):
self.add_sec()
def __str__(self):
return (f"{self.hrs}:{self.mins}:{self.secs}")
def __repr__(self):
return (f"{self.hrs}:{self.mins}:{self.secs}")
t = time(23,59,59)
print(t)
#23:59:59
t.increment()
print(t)
#0:0:0
t = time(0,0,90)
print(t)
#0:1:30
You can run this code yourself here
I made a super rudimentary stopwatch in python, just to get myself more acclimated with it, (It's my first programming language)and I've been trying to get the code to stop running when a key is pressed (using keyboard interrupt) but the code basically ignores keyboard interrupt and keeps going on forever.
(here's my code for reference)
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0
# Begin Process
timeloop = True
while timeloop == True:
try:
Sec += 1
print(str(Hour) + " Hrs " + str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
if Min == 60:
Sec = 0
Min = 0
Hour += 1
print(str(Hour) + " Hours")
except KeyboardInterrupt:
sys.exit(0)
Use a second thread (https://en.wikipedia.org/wiki/Multithreading_(computer_architecture), How to use threading in Python?):
def quit_on_user_input():
input = raw_input("Press any key to quit.")
# thread will lock up and wait for user to input. That's why this is on a separate thread.
sys.exit(0)
quit_thread = threading.Thread(target=quit_on_user_input, args=[])
quit_trhead.start()
# The rest of your code. quit_thread will run in the background and therefor won't lock up your main thread.
The KeyboardInterrupt exception is thrown when the user quit's the program with ctrl + c. You will need to use another method to detect a key press. This answer seems to have a good cross-platform class to check stdin.
EDIT: The answer I linked above would require the user to press enter, so that could work if you run it in a different thread.
The following method should work on any keypress but only on Windows.
import msvcrt
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0
# Begin Process
while True:
try:
Sec += 1
print(str(Hour) + " Hrs " + str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
if Min == 60:
Sec = 0
Min = 0
Hour += 1
print(str(Hour) + " Hours")
if msvcrt.kbhit():
break
except KeyboardInterrupt:
break
EDIT2: Found a library for kbhit that has cross-platform support. In the example below I have saved it in the same directory as kbhit.py and have imported it at line #1.
from kbhit import KBHit
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0
k = KBHit()
# Begin Process
while True:
try:
Sec += 1
print(str(Hour) + " Hrs " + str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
if Min == 60:
Sec = 0
Min = 0
Hour += 1
print(str(Hour) + " Hours")
if k.kbhit():
break
except KeyboardInterrupt:
break
I am writing a program where the user inputs two values: the number of minutes fast per hour that two clocks are. The output should be the time displayed on the clocks when the two clocks are showing the same time. The clocks are only checked once an hour (according to an accurate clock).
At the moment, I have:
clock1 = 0
clock2 = 0
inp = input(">").split(" ")
offset1 = int(inp[0])+60
offset2 = int(inp[1])+60
def add():
global clock1
global clock2
clock1 += offset1
if clock1 > 1399:
clock1 -= 1440
clock2 += offset2
if clock2 > 1399:
clock2 -= 1440
add()
while clock1 != clock2:
add()
hours = 0
while clock1 > 59:
hours += 1
clock1 -= 60
while hours > 23:
hours -= 24
hours = str(hours)
minutes = str(clock1)
if len(hours) == 1:
hours = "0" + hours
if len(minutes) == 1:
minutes = "0" + minutes
print(hours + ":" + minutes)
This works, but when the input values get big, it takes too long. How can I make this solution more efficient?
How can I create a countdown clock in Python that looks like 00:00 (min & sec) which is on a line of its own. Every time it decreases by one actual second then the old timer should be replaced on its line with a new timer that is one second lower:
01:00 becomes 00:59 and it actually hits 00:00.
Here is a basic timer I started with but want to transform:
def countdown(t):
import time
print('This window will remain open for 3 more seconds...')
while t >= 0:
print(t, end='...')
time.sleep(1)
t -= 1
print('Goodbye! \n \n \n \n \n')
t=3
I also want to make sure that anything after Goodbye! (which would most likely be outside of the function) will be on its own line.
RESULT: 3...2...1...0...Goodbye!
I know this is similar to other countdown questions but I believe that it has its own twist.
Apart from formatting your time as minutes and seconds, you'll need to print a carriage return. Set end to \r:
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print('Goodbye!\n\n\n\n\n')
This ensures that the next print overwrites the last line printed:
Here is the code which counts from 01:05 to 00:00 in MM:SS format.
Python 3 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j), end="\r")
else:
print(str(k)+str(i)+":"+str(k)+str(j), end="\r")
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("Goodbye!", end="\r")
time.sleep(1)
countdown(1,5) #countdown(min,sec)
Python 2 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print "\r"+str(k)+str(i)+":"+str(j),
else:
print "\r"+str(k)+str(i)+":"+str(k)+str(j),
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print "\rGoodbye!"
time.sleep(1)
countdown(1,5) #countdown(min,sec)
For the simplicity, this code is able to say you how long it takes until the next desired time, which might be whatever you want to do in your program. In your case, this is a kind of countdown timer.
from datetime import datetime
x=datetime.today()
y=x.replace(day=x.day+1, hour=3, minute=1, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
second = (secs % 60)
minut = (secs / 60) % 60
hour = (secs / 3600)
print ("Seconds: %s " % (second))
print ("Minute: %s " % (minut))
print ("Hour: %s" % (hour))
print ("Time is %s:%s:%s" % (hour, minut, second))
Then, output is as follows:
Seconds: 50
Minute: 32
Hour: 12
Time is 12:32:50
Good luck with your coding.
Maybe this link will help:
Making a Timer in Python 3
And look at my answer, it is same for your too!
Anyway, here is answer:
import time
import os
hour = int(input('Enter any amount of hours you want -+==> '))
minute = int(input('Enter any amount of minutes you want -+==> '))
second = int(input('Enter any amount of seconds you want -+==> '))
time = hour*10800 + minute*3600 + second*60
print('{}:{}:{}'.format(hour,minute,second))
while time > 0:
time = time - 1
seconds = (time // 60) % 60
minutes = (time // 3600)
hours = (time // 10800)
print('Time Left -+==> ',hours,':',minutes,':',seconds,)
os.system("CLS")
if time == 0:
print('Time Is Over!')
Input:
Enter any amount of hours you want -+==> 0
Enter any amount of minutes you want -+==> 0
Enter any amount of seconds you want -+==> 10
Output # All are on the same line
Time Left -+==> 0:0:10
Time Left -+==> 0:0:9
Time Left -+==> 0:0:8
Time Left -+==> 0:0:7
Time Left -+==> 0:0:6
Time Left -+==> 0:0:5
Time Left -+==> 0:0:4
Time Left -+==> 0:0:3
Time Left -+==> 0:0:2
Time Left -+==> 0:0:1
Time Left -+==> 0:0:0
Time Is Over!
import time
import sys
print(' ')
print('Countdown Timer, By Adam Gay')
print(' ')
print('Instructions: Input time to countdown from.')
print(' ')
c=':'
hourz=input('Hours: ')
minz=input('Minutes: ')
secz=input('Seconds: ')
print(' ')
hour=int(hourz)
min=int(minz)
sec=int(secz)
while hour > -1:
while min > -1:
while sec > 0:
sec=sec-1
time.sleep(1)
sec1 = ('%02.f' % sec) # format
min1 = ('%02.f' % min)
hour1 = ('%02.f' % hour)
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + str(sec1))
min=min-1
sec=60
hour=hour-1
min=59
Print('Countdown Complete.')
time.sleep(30)