how can i see how much time is left to the clock? - python

here's my code:
import time
import datetime
from playsound import playsound
print("pls use the 24 hour time scale")
alarmHour = int(input("what time do you want to wake up? "))
alarmMin = int(input("what min do you want to wake up at? "))
while True:
if(alarmHour == datetime.datetime.now().hour and
alarmMin == datetime.datetime.now().minute):
while True:
playsound("D:/Soul and Mind - E's Jammy Jams.mp3")
print("time for some coffee sleepy head")
break
else:
print("i'm not there yet")
time.sleep(10)
it's just a simple alarm clock that when it hit's a certain time it plays a sound.
and untill then every 10sec it prints "i'm not there yet" and i want to make a count down to the alarm. right next to the ("i'm not there yet"). how can i do that?

You could do it with a simple math calculation.
while True:
if(alarmHour == datetime.datetime.now().hour and
alarmMin == datetime.datetime.now().minute):
while True:
playsound("D:/Soul and Mind - E's Jammy Jams.mp3")
print("time for some coffee sleepy head")
break
else:
hoursLeft = alarmHour - datetime.datetime.now().hour
if hoursLeft <= 0:
hoursLeft += 24
minsLeft = alarmMin - datetime.datetime.now().minute
if minsLeft < 0:
minsLeft += 60
print (f'{hoursLeft}h{minsLeft}m left till the alarm')

Related

Is it possible to convert this Python CLI application into a Django app?

I created a python application that takes input from a user for hours and minutes and then displays an onscreen notification when the system has reached the time of the total hours and minutes.
I wanted to turn this into a web application with the use of Django is this possible?
import time
import os
from threading import Thread
def userTimeSet():
while True:
try:
hours = int(input("Number of hours? "))
minutes = int(input("\nNumber of minutes? "))
if hours > 0 and minutes > 0:
interval_sec = (hours*3600)+(minutes*60)
print(f"hours and minutes to seconds checking: {interval_sec}")
elif hours > 0 and minutes == 0:
interval_sec = (hours*3600)
print(f"hours to seconds checking: {interval_sec}")
elif hours == 0 and minutes > 0:
interval_sec = (minutes*60)
print(f"minutes to seconds checking: {interval_sec}")
else: print("invalid.")
futureTime = timeConfirmation(hours, minutes)
# create and start the daemon thread
print('Starting background task...')
daemon = Thread(target=timeCheck, args=(futureTime, interval_sec,), daemon=True, name='Background')
daemon.start()
print('Main thread is carrying on...')
time.sleep(interval_sec)
print('Main thread done running.')
break
except ValueError:
print("Enter a number.")
def timeConfirmation(hours, minutes):
print(f"{hours}:{minutes} (hours:minutes)")
currentDateTime = time.ctime()
print(f"\n Current Date and Time: {currentDateTime}")
timeInSeconds = (hours * 3600) + (minutes * 60)
futureTime = time.time() + timeInSeconds
print(f"\n Timer Ends at: {time.ctime(futureTime)}")
return futureTime
def timeCheck(futureTime, interval_sec):
while True:
time.sleep(interval_sec)
currentTime = time.time()
if time.ctime(currentTime) == time.ctime(futureTime):
alarmNotification()
print(f"Checking time. {time.ctime(currentTime)}")
def alarmNotification():
os.system("""
osascript -e 'display notification "{}" with title "{}" sound name "{}"'
""".format(f"Current time is: {time.ctime()}", "Its Break Time Boi", "Boop"))
userTimeSet()

User input to stop while loop

I'm currently making a stopwatch function, where the user has to input 1 to start and 2 to stop the stopwatch. I'm wondering how to implement the stop function when the while loop is going on as whatever I tried didn't work.
This is the stopwatch code I'm working on:
second = 0
minute = 0
hour = 0
millisecond = 0
start = input("Press 1 to start and 2 to stop: ")
while True:
if start == "2":
break
else:
print("%02d : %02d : %02d "%(hour, minute, second,))
time.sleep(1)
second += 1
if second == 60:
minute += 1
second -= 60
if minute == 60:
hour += 1
minute -= 60
input is blocking until the user types something (and hit enters).
So if you put it in your while loop, the user will get asked repeatedly if he wants to stop, each time pausing the clock, it is not what is expected.
But if you put the input outside the loop (it is strange that you do that), then the user is never asked to type something until the loop ends (which is never).
It means that in your case, input is not a solution.
There is a very similar question which has an accepted answer (slightly adapted to your case) :
try:
while True:
print("%02d : %02d : %02d "%(hour, minute, second,))
...
except KeyboardInterrupt:
# here the loop has definitely stopped
...
which works with Ctrl+C, being a standard way to signal the program to stop something.
If you want to use something other than Ctrl+C, there are other questions here on StackOverflow that could fit your needs :
detecting any keypress in a terminal : How to break this loop in Python by detecting key press
How to kill a while loop with a keystroke?
Your question is thus a duplicate of one of these.
Here's a threading example that does what you describe.
import time
import threading
thread_live = False
def countdown():
seconds = 0;
while thread_live:
hour = seconds // 3600
minute = (seconds // 60) % 60
second = seconds % 60
print("%02d:%02d:%02d "%(hour, minute, second))
seconds += 1
time.sleep(1)
print("exiting")
while True:
start = input("Press 1 to start and 2 to stop, 3 to exit: ")
if start == "1" and not thread_live:
cd = threading.Thread(target=countdown)
thread_live = True
cd.start()
elif start == "2" and thread_live:
thread_live = False
cd.join()
elif start == "3":
break
Here's a version that uses a timedelta to store and format the time:
import time
import datetime
import threading
thread_live = False
def countdown():
t = datetime.timedelta(0)
one = datetime.timedelta(seconds=1)
while thread_live:
print(str(t))
t += one
time.sleep(1)
print("exiting")
while True:
start = input("Press 1 to start and 2 to stop, 3 to exit: ")
if start == "1" and not thread_live:
cd = threading.Thread(target=countdown)
thread_live = True
cd.start()
elif start == "2" and thread_live:
thread_live = False
cd.join()
elif start == "3":
break

How to stop 'enter spamming' in a python reaction timer

I have been trying to make a reaction timer for a project to test reaction times. It uses 'perf_counter' to record the times before and after an input to test how long it takes to press the enter key. The issue is that the enter key can be spammed which makes it seem if they have a reaction time of 0.000001 seconds. I have made a class which disables the keyboard and enables it when I want. Even in that case, people are able to sneak in extra enter presses between the disables and enables. I have attached the code below. Any ideas how to prevent enter spamming?
import time, random, msvcrt
from math import log10, floor
def round_sig(x, sig=5):
return round(x, sig-int(floor(log10(abs(x))))-1)
class keyboardDisable():
def start(self):
self.on = True
def stop(self):
self.on = False
def __call__(self):
while self.on:
msvcrt.getwch()
def __init__(self):
self.on = False
import msvcrt
disable = keyboardDisable()
disable.start()
print('When I say __GO__ you hit ENTER! This will happen 3 times. Got it?')
time.sleep(2)
print('Ready')
time.sleep(1)
print('Steady')
time.sleep(random.randint(2,5))
print('#####__GO__######')
disable.stop()
tic = time.perf_counter()
a = input()
toc = time.perf_counter()
if msvcrt.kbhit():
disable.start()
timeSpent = toc-tic
print('Your first time was '+str(timeSpent) + ' seconds')
time.sleep(1)
print('The next one is coming up.')
time.sleep(1)
print('Ready')
time.sleep(1)
print('Steady')
time.sleep(random.randint(2,5))
print('#####__GO__######')
disable.stop()
tic2 = time.perf_counter()
b = input()
toc2 = time.perf_counter()
if msvcrt.kbhit():
disable.start()
timeSpent2 = toc2-tic2
print('Your second time was '+str(timeSpent2) + ' seconds')
time.sleep(1)
print('The last one is coming up.')
time.sleep(1)
print('Ready')
time.sleep(1)
print('Steady')
time.sleep(random.randint(2,5))
print('#####__GO__######')
disable.stop()
tic3 = time.perf_counter()
c = input()
toc3 = time.perf_counter()
timeSpent3 = toc3-tic3
print('Your last time was '+str(timeSpent3) + ' seconds')
average = (timeSpent + timeSpent2 + timeSpent3)/3
numAverage = round_sig(average)
print('Your average time is '+str(numAverage) + ' seconds')
The keyboard-disabling code never really runs.
Here's a simplification of your program that uses a function to capture one reaction time and calls it thrice.
The clear_keyboard_buffer() function (that should consume all outstanding keystrokes) was borrowed from https://stackoverflow.com/a/2521054/51685 .
import time, random, msvcrt, math
def round_sig(x, sig=5):
return round(x, sig - int(math.floor(math.log10(abs(x)))) - 1)
def clear_keyboard_buffer():
while msvcrt.kbhit():
msvcrt.getwch()
def get_reaction_time():
print("Ready")
time.sleep(1)
print("Steady")
time.sleep(random.randint(2, 5))
print("#####__GO__######")
clear_keyboard_buffer()
tic = time.perf_counter()
a = input()
toc = time.perf_counter()
return toc - tic
print("When I say __GO__ you hit ENTER! This will happen 3 times. Got it?")
time1 = get_reaction_time()
print(f"Your first time was {time1} seconds")
time.sleep(1)
print("The next one is coming up.")
time2 = get_reaction_time()
print(f"Your first time was {time2} seconds")
time.sleep(1)
print("The last one is coming up.")
time3 = get_reaction_time()
print(f"Your first time was {time3} seconds")
average = (time1 + time2 + time3) / 3
print(f"Your average time is {round_sig(average)} seconds")
This solution uses a Thread to start the timer, while the main thread waits for input all the time. That way, it is possible to catch early key presses:
from threading import Thread
import random
import time
def start():
global started
started = None
time.sleep(random.randint(2,5))
print("#### GO ####")
started = time.time()
t = Thread(target=start)
print("ready...")
# start the thread and directly wait for input:
t.start()
input()
end = time.time()
if not started:
print("Fail")
else:
print(end-started)
t.join()

datetime module not matching int comparison to int

I'm currently making an Alarm Clock as a tool to further learn python3 and I have come across a problem.
def clockCheck():
#get the hour and time from setAlarm
splitTime = re.compile(r'(\d+?)(:)(\d+)')
timeRe = splitTime.search(setAlarm())
alarmHour = timeRe.group(1)
alarmMinute = timeRe.group(3)
#get the live time
now = datetime.datetime.now()
currentHour = now.hour
currentMinute = now.minute
currentSecond = now.second
print(currentHour)
print(alarmHour)
while True:
if currentHour != alarmHour:
print("check1")
time.sleep(60-currentSecond) #if this isn't done, the alarm could be off by a couple seconds. Line's up things
time.sleep((60*60) - (60*currentMinute)) #this sleeps the program until the next hour is hit and reruns a check
elif currentMinute != alarmMinute:
print("check2")
time.sleep(60-currentSecond) #sleep until the next minute and rerun the check
#play sound
#break out of program, it's done
In this code snippet, when currentHour is compared to alarmHour (the first if statement), even when those two variables are the same, the code executes the if statement in which they do not equal each other.
In other words, if currentHour = 1 and alarmHour = 1, the code will execute as if currentHour != alarmHour and will run that if statements code.
Obviously that doesn't make sense and I don't know why that is happening when clearly 1==1. I have posted the full code, feel free to play with it. All these modules are built into python3.6
Here is my full code
'''
alarmclock.
ask user for what time to blare off
compare current time to set alarm time
if they do not equal the same then sleep the program for x time and ` rerun the check where it checks if current time is equal alarm time yet. loop until currenttime equals alarm time. then play soun`d
'''
import time
import datetime
import re
def setAlarm():
print("Hello, what time would you like the alarm to sound? Please input in this format\ne.g. 7:45pm\n")
time = input("Time: ")
splitTime = re.compile(r'(\d+?)(:)(\d+?)(pm|am)') #split up time inputted for manipulation
timeRe = splitTime.search(time)
hour = int(timeRe.group(1))
minutes = int(timeRe.group(3))
dayOfTime = timeRe.group(4).lower() #set pm or am to lowercase for ease
#errorChecking for proper time format
if hour > 12 or hour < 1:
print("Please input your time properly, in 12 hour time")
setAlarm()
if minutes > 59 or minutes < 0:
print("Please input your time properly")
setAlarm()
#if time of day is pm, then reassign all values from 1pm - 11:59pm as 13, 14, 15, etc 24 hour bullshit.
if dayOfTime == "pm" and hour != 12:
convertedHour = hour + 12
else:
convertedHour = hour
if dayOfTime == "am" and hour == 12:
convertedHour = 24
finalTime = str(convertedHour) + ":" + str(minutes)
print(finalTime)
return finalTime
def clockCheck():
#get the hour and time from setAlarm
splitTime = re.compile(r'(\d+?)(:)(\d+)')
timeRe = splitTime.search(setAlarm())
alarmHour = timeRe.group(1)
alarmMinute = timeRe.group(3)
#get the live time
now = datetime.datetime.now()
currentHour = now.hour
currentMinute = now.minute
currentSecond = now.second
print(currentHour)
print(alarmHour)
while True:
if currentHour != alarmHour:
print("check1")
time.sleep(60-currentSecond) #if this isn't done, the alarm could be off by a couple seconds. Line's up things
time.sleep((60*60) - (60*currentMinute)) #this sleeps the program until the next hour is hit and reruns a check
elif currentMinute != alarmMinute:
print("check2")
time.sleep(60-currentSecond) #sleep until the next minute and rerun the check
#play sound
#break out of program, it's done
def main():
clockCheck()
main()

Trouble with inputs and sleep.time()

I'm trying to make a little text based game, but I am having trouble with a while loop. I have experimented for many hours now! I would much appreciate it if you could kindly help me out. Thank-you for reading :D
I basically want it so that the user has to press a button before the timer runs out, and if he doesn't do it in time then the bear eats him. :')
Here is my code:
import time
cash = 0
def dead():
print("You are dead!")
main()
points = 0
def adventure_1(inventory, cash):
points = 0
time1 = 2
if time1 < 3:
time.sleep(1)
time1 -= 1
bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")
#Ran out of time death
if time1 == 0:
dead()
#Climb away from bear
elif bear == 'c' or 'C':
print("Your safe from the bear")
points += 1
print("You recieved +2 points")#Recieve points
print("You now have : ",points,"points")
adventure_2()#continue to adventure 2
#Invalid input death
elif bear != 's' or 'S':
dead()
def adventure_2(inventory, cash):
points = 2
time = 5
In python the input statement makes it so the programs flow waits until the player has entered a value.
if time1 < 3:
time.sleep(1)
time1 -= 1
#line below causes the error
bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")
To over come this you can use something similar to the code below which is a working example. We can over come the break in the program flow by using a Timer to see if the player has inputted anything, if he has not we catch the exception and continue with the programs flow.
from threading import Timer
def input_with_timeout(x):
t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
answer = input("enter answer : ")
except Exception:
print 'pass\n'
answer = None
if answer != True:
t.cancel()
def time_up():
print 'time up...'
input_with_timeout(5)
So as you can see we can over come the issue of waiting for our player to input a value by using a timer to count how long the player is taking, then proceeding to catch the exception from no input being sent, and finally, continuing with our program.
t_0 = time.time()
bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")
if abs(t_0 - time.time()) > time_threshold:
#player has died

Categories

Resources