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

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"

Related

Can't figure out why I cannot invalidate an input if it is not YYYY-MM-DD in python

What I'm trying to do is get an input in the YYYY-MM-DD specific format and it will output the amount of minutes someone has lived since their birthdate. But the function "invalidate" only seems to create errors. Without it the code works as long as you input the correct format. I've tried some regex code but haven't been able to make it work either. Also, would it be easier to do this within a class?
import datetime
import inflect
import sys
import re
##class Date:
##def __init__(self, year, month, day):
def main():
birth = input("Birthdate: ")
##birthdate = invalidate(birth)
print(num_to_words(days_between(format_date(birth))) + " minutes")
##def invalidate(x):
#if x != "%Y-%m-d":
#sys.exit("Invalid")
def format_date(e):
year, month, day = map(int, e.split('-'))
date1 = datetime.date(year, month, day)
return date1
def days_between(f):
today = datetime.date.today()
diff = today - f
x = diff.days * 24 * 60
return x
def num_to_words(x):
p = inflect.engine()
words = p.number_to_words(x)
return words
if __name__ == "__main__":
main()
You need to check it with strptime to see if it actually matches the format, not the exact string:
import datetime
def invalidate(x):
# You were missing the % on d
try:
datetime.datetime.strptime(x, r'%Y-%m-%d')
except ValueError:
return False # Or change this to exit
return True # You could return your datetime object here too
>>> invalidate('2022-06-05')
True
>>> invalidate('2022-6-05')
True
>>> invalidate('')
False
>>> invalidate('2022')
False
In your original function, you were checking the exact match of the string:
>>> invalidate('%Y-%m-d') # This was the only thing that would match
>>> invalidate('2022-6-5')
Invalid
Modify your invalidate function to this:
def invalidate(x):
if re.match(r'^\d{4}-\d{2}-\d{2}$', x):
if datetime.datetime.strptime(x, '%Y-%m-%d'):
return datetime.datetime.strptime(x, '%Y-%m-%d')
else:
print("Invalid date")
sys.exit()
else:
print("Invalid date")
sys.exit()
I have modified my code which now has an additional valid date check after valid format check.

How do I make my timer function override 'Enter value: '?

I created a small app where the user can add number of instances and then add arbitrary numbers, making it all end up in a pandas df. However, attempting to challenge the user doing aforementioned process, the user ends up being able to complete the process of adding values. This should stop abruptly, if time deadline is not met.
Try run the code yourself:
import time
import pandas as pd
# define the countdown func.
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
a = int(input("Enter number of instances: "))
test3 = []
i = 0
while i < a:
pl = int(input("Enter arbitrary integer: "))
test3.append(pl)
i += 1
print(list(test3))
DF1 = pd.DataFrame(test3)
return DF1
time.sleep(1)
t -= 1
print('Game over')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
print(countdown(int(t)))
I'd suspect that I am missing an if-statement, but that is potentially what I need help doing or...?
Any help is appreciated...thx
EDIT:
import pandas as pd
from threading import Timer
timeout = 8
t = Timer(timeout, print, ['Game over'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
a=int(input("Enter number of instances: "))
test3=[]
i=0
while i < a:
pl=int(input("Enter arbitrary integer "))
test3.append(pl)
i+=1
print(list(test3))
DF1 = pd.DataFrame(test3)
print(DF1)
t.cancel()

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

python - datetime output time only

The function below takes in HH:MM:SS but returns the date. I just want to enter the time and get out the time.
desired:
enter 23:23:23 > returns 23:23:23
currently:
enter 23:23:23 > returns 1900-01-01 23:23:23
question:
How do i get it to return only 23:23:23 time.
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Completed Code:
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
d = d.time()
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Use datetime.time() to get the time.
Example -
>>> d = datetime.datetime.strptime("23:23:23","%H:%M:%S")
>>> d.time()
datetime.time(23, 23, 23)

How To Have User Input Date and Subtract from It

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.

Categories