Very basic alarm clock does not open webbrowser - python

I'm totally new to programming. Wanted to write this basic alarm clock with Python but the webbrowser just doesn't open. I think it is probably my if statement that doesn't work. Is that correct?
from datetime import datetime
import webbrowser
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
now = datetime.today()
print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))
if now.hour == alarm_h and now.minute == alarm_m:
webbrowser.open(alarm_sound, new=2)

You can try this simple example.
from datetime import datetime
import webbrowser
import threading
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
print alarm_sound
now = datetime.today()
def test():
webbrowser.open(alarm_sound)
s1 = '%s:%s'
FMT = '%H:%M'
tdelta = datetime.strptime(s1% (alarm_h, alarm_m), FMT) - datetime.strptime(s1%(now.hour, now.minute), FMT)
l = str(tdelta).split(':')
ecar = int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
print ecar
threading.Timer(ecar, test).start()
We use threading to open a webbrowser after n seconds. in you example you ask user for hour and minute, in this way we calculate diffrence between two times using just hours and minutes.
If you need more explanation just comment.

Your current code looks like it is checking the current time against the set alarm time. However, you currently have just one check, but you need to either loop and continuously compare the current time with the set alarm time or use another method of continuously checking.
The webbrowser line does work. Its not executing because the current time never reaches the alarm time (since you are not continuously comparing the current time with the set alarm time).
Try:
from datetime import datetime
import webbrowser
name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
now = datetime.today()
print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))
webbrowser.open(alarm_sound, new=2) #Added temporarily to test webbrowser functionality
if str(now.hour) == alarm_h and str(now.minute) == alarm_m: #Converted integer type to string type to match datatype of alarm_h and alarm_m
webbrowser.open(alarm_sound, new=2)
This should open the webbrowser so you can test its functionality.
I also converted now.hour and now.minute to type string to match the datatypes of alarm_h and alarm_m. They were both integers and which can't be directly compared to a string datatype.
Definitely look into looping or threads for continuously updating the current time and checking if it equals the current thread.

Related

Terminate loop after a certain amount of time

I am trying to write a program that will measure a user's typing speed however I cannot get the loop where the user inputs to terminate when the time is up. I want the loop to stop as soon as the time is finished.
from datetime import datetime, timedelta
text = 'Hello My name is matthew'
def some_function(duration):
end_time = datetime.now() + timedelta(seconds=duration)
while datetime.now() < end_time:
answer = input('Type the following: ' + text + '\n\n')
duration = int(input('How long do you want to test yourself: '))
some_function(duration)
The problem is that input() is blocking. The rest of the code isn't executed until the user submits their input by pressing enter. You should check out this thread for non-blocking console input

How to limit the time input to only be accpetable within a timeperiod in Python

I have succesfully made a function that asks the user for a valid time by importing the module Datetime. If the user doesn't enter a valid time the question will be asked until he/she does.
But the problem is that im currently running a zoo, who has open between 08:00 - 22:00. How do I extend my code so the user only can enter a valid time between that timeperiod? Help would be appreciated.
Code:
def input_time():
while True:
try:
time = input("What time do you plan to be here? (HH:MM): ")
pattern_time = ('%H:%M')
time = datetime.strptime(time, pattern_time)
except ValueError:
print("Not a valid time,try again")
continue
else:
break
return time
time = input_time()
Sorry no one has answered this. The time_struct provides member fields that you can test:
while True:
try:
t = input("What time do you plan to be here? (HH:MM): ")
pattern_time = ('%H:%M')
t = time.strptime(t, pattern_time)
if not (8 <= t.tm_hour <= 22):
print("The zoo is only open from 8:00 to 22:00")
continue
except ValueError:
print("Not a valid time, try again")
continue
else:
break
return t
Also, be careful with variable names.

Is there any way to set time to notify?

I want to set time to notify the user by a flexible time I mean I want to input a time.
I can get my desire output with a specific time, but when I input my desired time, It does not go through the program. again ask for input time:
I need to print the time and notify and continue the program:
20:24:00
>
>>> from win10toast import ToastNotifier
>>> import time
>>> def run_app():
>>> show_help()
>>> while True:
>>> #set time to notify for shopping
>>> notification_time = time.strftime("%H:%M:%S")
>>> if notification_time == input("Please enter a specific time:\n"):
>>> print(notification_time)
>>>
>>> break
>>> else:
>>> pass
>>> #organise the notification
>>> notification1= ToastNotifier()
>>> notification1.show_toast("Alarm","It is time to shop ")
the result now is:
Please enter a specific time:
20:24:00
Please enter a specific time:
...
The logic of your input loop is faulty. It does not at all match what you say you want to do:
notification_time = time.strftime("%H:%M:%S")
# This stores the current time, mis-named "notification_time"
if notification_time == input("Please enter a specific time:\n"):
# This requires the user to enter a time in the required format.
# If that doesn't match the current time at the previous instruction,
# you ignore the input and repeat the process.
Finally, if the user does manage to enter the current time while it is still current, you take that as the notification time. The user has no way to enter a time in the future.
Instead, you need to accept the user's notification time, and then check that format for validity. The easiest way is usually to accept the input string, and then use a try/except block to convert it to a time. If that fails you loop back to try the input again.
I've tried to make your idea into a functional code:
from datetime import datetime
import time
from win10toast import ToastNotifier
toaster = ToastNotifier()
# Validate if the format of the time that the user submitted is correct
def isTimeCorrect(input):
try:
time.strptime(input, '%H:%M:%S')
return True
except ValueError:
return print('time is wrong')
# Request the user to type the alarm time
alarm = input('Type your alarm time in this format HH:MM:SS\n')
# Get the current time
now = datetime.now()
# Format the current time
current_time = now.strftime("%H:%M:%S")
# Loop and check the current time until it's the same as the alarm
while (isTimeCorrect(alarm)):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# Check if the current time is the same as the alarm
if current_time == alarm:
# throw the notification
toaster.show_toast("Example","Notifcation Text",icon_path=None,duration=5,threaded=True)
break

How to use sched run at given time and number of times?

How can I use sched to run function test()at user given time i and runtime? I am not sure the what parameter should put it in sched.scheduler(time.time, time.sleep).
It is an example:
from datetime import datetime
i = str(raw_input('What date to start function: '))
runtime = raw_input('How many times to run: ')
try:
dt_start = datetime.strptime(i, '%Y-%m-%d-%H-%M-%S')
except ValueError:
print "Incorrect format"
def test():
print "Hello World"

python expire input prompt after timeout [duplicate]

This question already has answers here:
Time-Limited Input? [duplicate]
(2 answers)
Closed 6 years ago.
How do I make an offer/question expire in python, e.g.
import time
print("Hey there man.")
test = input()
if test == "Hey" or test == "Hi":
print("Hey there dude.")
elif test == "Go away" or test == "Bye":
print("Cya dude.")
How would I make this offer say I don't know only last 10 seconds before it ignores the if and elif statements and prints something completely new as in something similiar to...
import time
print("Hey there.")
test = input()
if test == "Hey" or test == "Hi":
print("Hey there dude.")
elif test == "Go away" or test == "Bye":
print("Cya dude.")
else time.sleep == >5:
print("Nah your time has expired I'm out anyways.")
Edit #2
Well scratch everything. I seriously over-complicated the problem. Sci Prog just posted a much simpler solution. Although I would change a few things like so.
import time
expires_in = 5 #in seconds
start = time.time()
test = input("Hey there.\n") #\n is a newline character
end = time.time()
if end - start > expires_in:
print("Nah your time has expired I'm out anyways.")
elif test == "Hey" or test == "Hi":
print("Hey there dude.")
elif test == "Go away" or test == "Bye":
print("Cya dude.")
Original Answer
This kind of does the trick. If it takes longer than the timeout period for the user to respond, than when they do get around to entering their input I print out a message saying it took to long.
However, because the input command pauses execution of the script until we get some input from the user, we cannot easily interject a message until they have entered something. There are two ways around this. 1) Instead of using input we use some lower level functions and we work with sys.stdout directly. 2) We multi-thread the script. Both of these methods are complicated, and are probably more work than you would want to get yourself into.
import time
def get_input():
start_time = time.time()
expires_in = 5 #in seconds
got = ""
while (time.time() - start_time < expires_in):
if got:
print("you entered", got)
return got
got = input("enter something: ")
print("You took to long")
Edit:
The OP asked for an example that better follows what he was trying to accomplish, so here it is. I've added an explanation after the code as well.
import time
print("Hey there.")
def get_input():
start_time = time.time()
expires_in = 5 #in seconds
user_input = ""
while (time.time() - start_time < expires_in): #keep looping if the time limit has not expired
if user_input:
return user_input
user_input = input()
print("Nah your time has expired I'm out anyways.")
test = get_input()
if test == "Hey" or test == "Hi":
print("Hey there dude.")
elif test == "Go away" or test == "Bye":
print("Cya dude.")
time.time() will grab whatever the current time is. (returned as a big nasty number that represents the number of seconds since 0 BC).
Once we enter the while loop we don't have any user input yet so we can skip straight to the input statement. Then depending on how fast of a typer the user is we can have two outcomes.
a) The user responds in time. In this case we execute the while loop again. This time we enter the if user_input: if clause and we immediately return whatever the user inputted
b) The user does not respond in time. In this case we will not re-execute the while loop, and as a result we will continue to the print("Nah your time has expired I'm out anyways.") print statement.
I would like to note that it is important that we placed the input statement where we did. If we checked for user input after the user gave it to use, we would end up with the following scenario: The question expires, but the user still gives us some input. We see that the user gave us some input so we return the input. And then we never get a chance to tell the user the time has expired.
Also a nice little tip you could implement. You can make the input case-insensitive, by using input().lower() instead of input(). You would then have to change your if statements to be lower case as well. The user would then be able to type in either Hey or hey or something weird like hEy if they really wanted to.
You can use datetime objects (from the module with the same name). Computing the differences gives a timedelta object.
Finally, you must test for the delay before checking for the answers.
from datetime import datetime
print("Hey there.")
dt1 = datetime.now()
test = input()
dt2 = datetime.now()
difference = dt2 - dt1 # this is a timedelta
if difference.seconds > 10 or difference.days > 0:
print("Nah your time has expired I'm out anyways.")
elif test == "Hey" or test == "Hi":
print("Hey there dude.")
elif test == "Go away" or test == "Bye":
print("Cya dude.")
(runs in python 3, as specified in your question)
Of course, the .days part could be omitted, since it very unlikely that someone will wait that long :)

Categories