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)
Related
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")
I have this working code that checks a conditions every 3 minutes considering the local time, so every 0, 3, 6, 9.....It prints "checking condition".
import time
def get_next_time():
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
return result
next_run = get_next_time()
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#some condition
next_run = get_next_time()
time.sleep(1)
The problem is that I need the code without functions, so I need to find a way to write this code without using any funcion, and I cannot use break or interrput the loop
I tried:
while True:
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
time.sleep(1)
But it does not work: it does not do nothing.
Any ideas?
you can compact the function in one statement:
import time
next_run = (3 - (time.localtime().tm_min % 3) + time.localtime().tm_min)%60
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#checking conditions...
next_run=(3 - (time.localtime().tm_min % 3) + time.localtime().tm_min)%60
time.sleep(1)
The first time, the get_next_time() will only be executed when next_run == now.tm_min. The second time, you execute it each loop
import time
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
while True:
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
time.sleep(1)
Rounding to the next multiple of 3 minutes contradicts the specification "every 0...".
It is enough to do
import time
first= True
while True:
minute= time.localtime().tm_min
if first or minute == target:
print("checking condition")
first= False
target= (minute + 3) % 60
time.sleep(1)
Update:
I modified the code so that a single call to localtime is made on every iteration, to make fully sure that the minutes do not change between the calls.
More compact but less efficient:
import time
while True:
minute= time.localtime().tm_min
if 'target' not in locals() or minute == target:
print("checking condition")
target= (minute + 3) % 60
time.sleep(1)
im fairly new with python but im tring to get a device to turn on for one minute and off for 3 minutes repeatedly from the times of 9am to 5pm and i can't get the if statement to reference the updated time from the loop any help would be greatly appreciated!!!
import datetime
import time
n = "on" #to be replaced with GPIO output
f = "off" #to be replaced with GPIO output
nt = "tis not be the time" #used to see if working or not
tt = "tis be time" #used to see if working or not
now = datetime.datetime.now()
hour = now.hour
def count():
now = datetime.datetime.now()
hour = now.second
total = 1
if hour >= 8 and hour <= 16:
now = datetime.datetime.now()
hour = now.hour
for i in range(1,100):
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.second
print (hour)
else :
for i in range(1,100):
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
count()
You could fix it with a while loop instead, it would look like this, just put all of it inside your function
now = datetime.datetime.now()
hour = now.hour
if hour >= 8 and hour <= 16:
run = True
else:
run = False
while run:
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.second
print (hour)
if hour >= 8 and hour <= 16:
run = True
else:
run = False
while run == False:
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
if hour >= 8 and hour <= 16:
run = True
else:
run = False
Maybe using a while statement. In addition, you have hour = now.second on the second line of the function count and I think it should be hour = now.hour.
See the code with comments:
import datetime
import time
n = "on" #to be replaced with GPIO output
f = "off" #to be replaced with GPIO output
nt = "tis not be the time" #used to see if working or not
tt = "tis be time" #used to see if working or not
#Next lines are redundant, commented out.
#now = datetime.datetime.now()
#hour = now.hour
def count():
now = datetime.datetime.now()
hour = now.hour #now.second
total = 1
while hour >= 8 and hour <= 16:
now = datetime.datetime.now()
hour = now.hour
# for i in range(1,100): -> why you need this?
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.hour #now.second
print (hour)
for i in range(1,100): #I don't know why you need a loop here
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
count()
Edited for correcting another hour = now.second inside the while loop
I don't know how are you planning on running the code, but the main problem I see is that you do not have any loop for your code to run infinitely and check the time condition.
Also it's not clear for me why you need this total variable that gets doubled.
Another thing is your for loops - the condition is not clear. Why do you want to run it in this specific range?
What I would do is I would create an infinite loop and inside it make some decisions based on a clear time conditions - the conditions that are specified by you.
So if I understood your case correctly I'd rather write something like this:
# between 9am to 5pm turn on the device for 60 seconds and off for 180 seconds repeatedly
from datetime import datetime
import time
def update_device_state(state):
# TODO: implement GPIO output code
pass
def run():
device_state = 'off'
new_state = device_state
on_timer = 0
off_timer = time.time() - 180 # initial value must be over 180 seconds to trigger device on a first run
while True:
hour = datetime.now().hour
if 5 <= hour <= 17:
if device_state == 'off' and time.time() - off_timer > 180:
on_timer = time.time()
new_state = 'on'
off_timer = 0
elif device_state == 'on' and time.time() - on_timer > 60:
off_timer = time.time()
new_state = 'off'
on_timer = 0
else:
if device_state = 'on'
new_state = 'off'
on_timer = 0
off_timer = time.time()
if device_state != new_state:
update_device_state(new_state)
device_state = new_state
time.sleep(1)
run()
But the code requires some testing as I just quickly drafted it and I just briefly red it.
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
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)