This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
I'm new to python, I can't tell if this will work or not
import time
from sys import stdout
varthing = 1
while varthing == 1:
time.sleep(1)
checker = time.strftime("\r%b, %d %H:%M:%S", time.localtime())
print checker,
stdout.flush()
if checker == "Dec, 25 00:00:00" :
print "It's Christmas"
raw_input("Enter anything to close\n")
varthing = 0
I don't see anything wrong. It is a clock the notifies you when Christmas is.
Your strftime format starts with \r. Why? The string you are testing against in the if statement will never match because it doesn't start with \r.
time.sleep(1) is not guaranteed to sleep for exactly one second. It might sleep longer and you'll miss the one-second window in which checker would match the string you're testing against.
If you don't need prints every second, this will do the trick:
import datetime, time
target_date = datetime.datetime(2011, 12, 25)
time_left = target_date - datetime.datetime.now()
time.sleep(time_left.total_seconds())
print "It's Christmas"
Related
This question already has answers here:
In Python, how can I put a thread to sleep until a specific time?
(14 answers)
Closed 2 years ago.
I have a list which contains times like this ['13:45','12:30','11:40'] in string format. So, the script should pick the earliest time in the string format list and wait till that time occurs. The first part of code, picking the minimum can be done with min function. How to make it wait till that time?
And also, if the time mentioned the least one already completed(past) then it should pick the next lowest.
There is a nuance in this problem: when the least time from the list is smaller than the current time. In this case, the most reasonable way is to sleep until the smallest time in the list tomorrow. E.g., let's consider current time 23:59 and tl = [00:10, 01:30], then the script should sleep until 00:10 (tomorrow).
Here is the solution:
import time
from datetime import datetime
from datetime import timedelta
from dateutil import parser
now = datetime.now()
def parse_times(tl):
for t in tl:
parsed_time = parser.parse(t)
if parsed_time > now:
yield parsed_time
else:
yield parsed_time + timedelta(days=1)
tl = ['13:45', '12:30', '11:40']
parsed_times = parse_times(tl)
next_time = min(parsed_times)
time.sleep((next_time - now).total_seconds())
What about something like:
from time import sleep
from datetime import datetime
tl = ['13:45','12:30','11:40']
## remove times less or equal current time, then get minimum
t = min(el for el in tl if el > datetime.now().strftime('%H:%M'))
## sleep until we pass the minimum time
## we check this every second
while t > datetime.now().strftime('%H:%M'):
sleep(1)
import time
import tkinter
import win10toast
toaster = win10toast.ToastNotifier()
t = time.localtime()
current_time = time.strftime("%H:%M", t)
workout_times = ['']
workout_time = str(input('What time do you want your reminder to come(Format is Hour:Minute): '))
workout_times.append(workout_time)
while current_time == current_time:
if current_time == workout_time:
print(2)
toaster.show_toast('Reminder', 'DO IT`', duration=10)
break
How would I be able to make python always check for the time? Like for you to input a time, for python to constantly check for the time and when it comes for it to run the if stament.
I agree with the comments above, yet I do think it is worthy to answer the question and show a way for comparing between the current time and a target time (if you do decide to run such a python code, I guess you’d want to run this in the background by calling your python script with pythonw.exe via command line or script). So below is one simple option for monitoring the time and executing a task:
from datetime import datetime
from time import sleep
sleep_period = 60
target_time = datetime(2020, 8, 10, 10, 33) # you can construct the numbers inside from user input
while True:
delta = datetime.today()-target_time
if delta.days == 0 and delta.seconds <= sleep_period:
print('It is time to execute a function')
break # or ask for another input…
sleep(sleep_period)
This question already has answers here:
How would I stop a while loop after n amount of time?
(11 answers)
Closed 9 months ago.
What is the best way to timeout while loop in python
say:
while not buff.endswith('/abc #'):
After 10 secs, if it does not match, break the loop.
Thanks
You can record the time before the loop, then inside the while loop you can compare the current time, and if it's > 10 seconds, you can break out of the while loop.
Something like:
from datetime import datetime
start_time = datetime.now()
print(start_time)
while not buff.endswith('/abc #'):
print('waiting')
time_delta = datetime.now() - start_time
print(time_delta)
if time_delta.total_seconds() >= 10:
break
If your only concern is to end the loop after 10 seconds, try the below code.
from datetime import datetime
t1 = datetime.now()
while (datetime.now()-t1).seconds <= 10:
#do something
print(datetime.now())
Else check for the time difference inside the loop and break it. Like,
t1 = datetime.now()
while not buff.endswith('/abc #'):
if (datetime.now()-t1).seconds > 10:
break
You can use interrupting cow package and put you code inside a with management statement.
import interruptingcow
TIME_WAIT=20 #time in seconds
class TimeOutError(Exception):
"""InterruptingCow exceptions cause by timeout"""
pass
with interruptingcow.timeout(TIME_WAIT, exception=TimeOutError):
while not buff.endswith('/abc #'):
pass #do something or just pass
As long you don't use interruptingcow with another systems that implements SIGALARM eg. stopit, python-rq. It will work
I'm trying to make a simple alarm using Python but whatever I try it doesn't seem to work. I've just recently made a timer but an alarm would be a little more useful.
I'm also pretty new to Python so I'm not really aware of all the rules and syntax.
import datetime
import os
stop = False
while stop == False:
rn = str(datetime.datetime.now().time())
print(rn)
if rn == "18:00:00.000000":
stop = True
os.system("start BTS_House_Of_Cards.mp3")
When I run the file, it prints the time but goes completely past the time I want the alarm to go off at.
The technical problem here is that if you call datetime.now() over and over again, you can't always call it fast enough to get all of the possible values. So == should instead be >=. However, this still isn't very good.
A much better way to do this is to use time.sleep() instead of looping.
import datetime
import os
import time
now = datetime.datetime.now()
# Choose 6PM today as the time the alarm fires.
# This won't work well if it's after 6PM, though.
alarm_time = datetime.datetime.combine(now.date(), datetime.time(18, 0, 0))
# Think of time.sleep() as having the operating system set an alarm for you,
# and waking you up when the alarm fires.
time.sleep((alarm_time - now).total_seconds())
os.system("start BTS_House_Of_Cards.mp3")
Just replace:
if rn == "18:00:00.000000":
With:
if rn >= "18:00:00.000000":
Use the following to round to the next minute (or adapt for seconds etc)
import datetime as dt
rn = dt.datetime.now()
# round to the next full minute
rn -= dt.timedelta( seconds = rn.second, microseconds = rn.microsecond)
rn += dt.timedelta(minutes=1)
To adapt for seconds remove seconds = rn.second and then change minutes in the next line to seconds
How it works
Removes the seconds and microseconds from the current time and then adds on 1 minute therefore rounding it to the next whole minute.
I Had the same issue for my IoT based project here is a simple tryout code written by me in python to invoke certain function at a given time here goes code
import datetime
from time import sleep
tempdatetimeobj = datetime.datetime.now()
try:
while True:
print("#################")
now = str(datetime.datetime.now().time()) # convert a time in string
print("Time is:- " + str(now))
timestring = now[:5]
# Slice the time for eg time is 17:02:52:23656 it will
slice it to 17:02 only
print("SLICE MAGIC :- "+ timestring)
if timestring == '17:26' : # after slicing operation only you can compare time
print('Triggered')
elif timestring == '17:30' :
print('again triggered')
else :
print('-_-')
sleep(60)
except KeyboardInterrupt:
print('unHandled Exception Occured')
How about using this technique? It's simple and works smoothly.
import datetime
import winsound # exclusively for windows only,
# if you are on any other system you can use 'playsound' or 'simpleaudio' module.
alarm_hour = int(input("Set hour: "))
alarm_minutes = int(input("Set minutes: "))
am_pm = input("am or pm? ")
print(f"Waiting for time: {alarm_hour}:{alarm_minutes} {am_pm}")
# time conversion
# because datetime module returns time in military form i.e. 24 hrs format
if am_pm == 'pm': # to convert pm to military time
alarm_hour += 12
elif alarm_hour == 12 and am_pm == 'am': # to convert 12am to military time
alarm_hour -= 12
else:
pass
while True: # infinite loop starts to make the program running until time matches alarm time
# ringing alarm + execution condition for alarm
if alarm_hour == datetime.datetime.now().hour and alarm_minutes == datetime.datetime.now().minute:
print("\nIt's the time!")
winsound.Beep(1000, 1000)
break
Obviously you can do more with the program by doing data validation for the inputs. Using the 'simpleaudio' module, you can add some interesting functions. And the number of other things you can do to increase the efficiency of the program.
There is another alternative that hasn't been mentioned which might work for you, depending on what your goals are: signal.alarm.
signal.alarm is similar to the alarm(3) library call on Unix where setting a time will result in a SIGALRM signal being sent to a parent process in the future to denote when an asynchronous action should be taken (the default with an uncaught signal is a dead process).
Example:
$ python
Python 2.7.16 (default, Mar 20 2019, 12:15:19)
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import signal
>>> signal.alarm(1)
0
>>> Alarm clock
The key points when using signal.alarm(..) is the following:
- The solution is best for a single process application; it should not be used if you need to have per-thread or multi-process timers.
- You will need to setup a signal handler for signal.SIGALRM.
The key point when handling signals is:
- Handle asynchronous
This approach is fairly basic and very OS-centric, but it's a simple, clean approach for doing things. There are other alternatives that could potentially be employed using the kqueue/select module (poll, etc, come to mind), other calls within the signal module, concurrent.futures/multiprocessing (there's a timeout option on some APIs).
Just one potential tool to use in your toolbox of timers.
A complete solution using signal.alarm can be found here (I adjusted the end time so I wouldn't have to wait forever for it to complete).
$ date; python3 play_house_of_cards.py ; date
Wed 10 Jul 2019 04:54:16 PM PDT
would have run `start BTS_House_Of_Cards.mp3`
Wed 10 Jul 2019 04:55:00 PM PDT
$
I would suggest using while loop with True like this:
loop = True
while loop:
rn = str(datetime.datetime.now().time())
if rn >= "18:00:00.00000":
loop = False
this alarm has almost every feature so it might be helpful for you if you want to make a perfect alarm
from pygame import mixer
from os import path
from sys import path as p
from time import sleep,strftime
try:
while True: #it will give you another chance if you fill in letters or symbols
hour=input('hour=')
if hour.isdigit():# if input is digit
if len(hour)==1:#if the input has one digit
hour2='0'+hour #it will add 0 in front of the input because time module gives 01 not 1 so it will convert 1(input) into 01
else:#if the input has two digit
hour2=hour
else:
print('press any key to try again')
min=input('Minute=')
if min.isdigit():
if len(min)==1:
min2='0'+min
else:
min2=min
ap=input('am/pm=')
if ap=='am' or 'pm' or 'AM' or 'PM' or 'Am' or 'Pm' or 'aM' or 'pM':
apm=ap.upper()
break
while True:
x=strftime('%I')
y=strftime('%M')
z=strftime('%p')
if x==hour2 and y==min2 and z==apm :
print("Type 'h' for help")
while True:
mixer.init()
you don't have to write the location of a file(c:\music\alone.mp3) just save the file in the same folder as the .py file
music_=(path.join(p[0],'alone.mp3' ))
mixer.music.load(music_)
mixer.music.play()
stop=input('X=')
if stop=='s' : #it will snooze the alarm for 5 min
time_=strftime('%I')
time2=strftime('%M')
time3=strftime('%S %p')
print('Alarm will sound at ',time_,':',int(time2)+5,':',time3)
mixer.music.stop()
sleep(300 )
elif stop=='h':
print("1.Type 's' for snooze alarm / 2.Press any key except 's' and 'h' for turn off the alarm" )
elif stop!='s' or 'h': #it will stop alarm
mixer.music.stop()
break
break
except:
print('Invalid Input: Please try again')
This question already has answers here:
How do I get the current time?
(54 answers)
Closed 6 years ago.
I would like to know a way to time between two points in a program. In my situation I will ask the user 10 questions and after display the time it took for them to answer the question (example code below). How would i do this through something like import time ?
Example code:
timer.start
question1 = input("What is your favorite game ?")
timer.end
print(timer.time)
^
The timer.x thing is going to be replaced with your suggestions.
import time
s=time.time()
question1 = input("What is your favorite game ?")
e=time.time()
print(e-s)
time.time() Returns the time in seconds since the epoch as a floating point number.
How about this?
from datetime import datetime
start = datetime.now()
question1 = input("What is your favorite game ?")
end = datetime.now()
print(str(end - start))