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
Related
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
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
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"
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.
What I want is a user input a selected date, and subtract that date from the current date, and then create a sleep timer according to the results.
from datetime import tzinfo, timedelta, datetime
def ObtainDate():
isValid=False
while not isValid:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
d1 = datetime.datetime.strptime(userIn, "%m/%d/%y")
isValid=True
except:
print "Invalid Format!\n"
return d1
t = (datetime.now() - d1).seconds
My current current code looks like this, but I cannot figure out how to get d1 and subtract the current date from it.
Since you are importing the class using
from datetime import tzinfo, timedelta, datetime
you are no longer importing the whole datetime module under that name, but individual classes directly into your script's namespace. Therefore your input parsing statement should look like this:
d1 = datetime.strptime(userIn, "%m/%d/%y") # You are no longer
The following will give you the difference in seconds between now and the entered time:
t = (datetime.now() - d1).total_seconds()
And as for the second part, there are many ways to implement a timer. One simple way is
import time
time.sleep(t)
EDIT
Here is the whole thing together:
from datetime import tzinfo, timedelta, datetime
def ObtainDate():
isValid=False
while not isValid:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
d1 = datetime.strptime(userIn, "%m/%d/%y")
isValid=True
except:
print "Invalid Format!\n"
return d1
t = (ObtainDate() - datetime.now()).total_seconds()
print t
Your code has a few simple errors. This version works (though I'm not sure exactly what you need, it should get you past your immediate problem).
from datetime import datetime
def ObtainDate():
while True:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
return datetime.strptime(userIn, "%m/%d/%y")
except ValueError:
print "Invalid Format!\n"
t0 = datetime.now()
t1 = ObtainDate()
td = (t1 - t0)
print t0
print t1
print td
print td.total_seconds()
Your main problem was that you were not calling your function. I have also simplified your while loop to an infinite loop. The return statement will break out of the loop unless it raises an error.