Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am making an alarm clock program that will have to sleep (Not make noise) until 6:00AM. The problem I am having is that I cannot get the program to wait X seconds
Pseudo Code:
X = 6:00AM - CurrentTime
time.sleep(X)
Here is my code so far:
#Imports
import datetime
import time
import pygame
WORDS = ["Wake", "Me", "Tommorow"]
#Make J.A.R.V.I.S. Listen
mic.activeListen():
#Determine time and difference of time
x = datetime.datetime.now()
x = x.total_seconds
print(x)
x = datetime.timedelta()
x = float(x) #time.sleep() Requires a float value.
time.sleep(x) #Sleeps until 6:00 AM
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
In order to create a datetime object representing 6:00am, you'd need to specify the date. E.g. if you want 6:00am today (assuming it happens in the future):
from datetime import datetime, date, time, timedelta
import time
d = date.today()
target_dt = datetime.combine(d, time(6,0))
td = target_dt - datetime.now()
time.sleep(td.total_seconds())
If you want 6am tomorrow, do:
d = date.today() + timedelta(days=1)
# the rest is the same...
You should not trust time.sleep() to stop waiting at the expected time, as any caught signal will terminate it (see answers to Upper limit in Python time.sleep()?).
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This prints current time, for 10 sec interval what function or loop I have to use
import time;
localtime = time.asctime(time.localtime(time.time()))
print "Local current time :", localtime
You should argoment better the question!
By the way if tou are trying to print every 10 seconds the current time for 10 times you can do it as:
import time
from datetime import datetime
#For 10 times
for x in range(10):
# Get current time
now = datetime.now()
# Make a string of it
current_time = now.strftime("%H:%M:%S")
# Print it
print(current_time)
# Wait for 10 seconds
time.sleep(10)
Output:
14:33:33
14:33:43
14:33:53
14:34:03
14:34:13
14:34:23
14:34:33
14:34:43
14:34:53
14:35:03
try using the time.sleep() method along with a loop that iterates 10 times for i in range(10)
import time
for i in range(10):
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
time.sleep(10)
a bit more advanced with proof that it works
import time
interval = 10
logged = []
for i in range(10):
localtime = time.localtime(time.time()).tm_sec
print ("Local current time :", localtime)
logged.append(int(localtime))
time.sleep(interval)
print(len([i for i in range(1,len(logged)) if logged[i-1] + interval == logged[i]])+1 == len(logged))
Local current time : 43
Local current time : 53
Local current time : 3
Local current time : 13
Local current time : 23
Local current time : 33
Local current time : 43
Local current time : 53
Local current time : 3
Local current time : 13
True
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I need a function returning a boolean indicating if midnight has just passed.
I came up with this but I am not happy with the "form". Can anyone think of anything better? as in terms of efficiency/elegance?
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.today # see other comment below
time_ago = time_now() - timedelta(minutes=delta)
# next line with a dummy delta (zero) cuz "datetime.today - timedelta(days=1)" gives an error
today = time_now() - timedelta(days=0)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight, 10)
datetime.today - timedelta(days=1) gives an error because datetime.today is a function that needs to be called. This is why you must have felt the need to write time_now() with parentheses: it's calling the function, twice (with different results, because time has a tendency to pass).
Avoid strftime in favour of date(), which returns the date part only (as a datetime.date object).
Use datetime.now() instead of datetime.today() so that subtracting a timedelta can take the timezone (and hence daylight savings time changeovers) into account.
So then you get this:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.now()
time_ago = time_now - timedelta(minutes=delta)
return time_now.date() != time_ago.date()
You probably misunderstood how to declare a function and how to call it.
Here is a version that fixed the issues with function calls:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
today = datetime.today()
time_ago = today - timedelta(minutes=delta)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight(10))
False
Be careful, this code doesn't take care of time zones. The behavior will be different from a location to another
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)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
At work we have to do our own time management and get controlled from time to time. Because I always forget, when I take my breaks and how long, I decided to write a python script which runs on startup and writes the current time after I haven't moved my mouse or typed on my keyboard for 5 minutes.
import datetime
def writetime():
t = datetime.datetime.now()
with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'a') as f:
f.write('%s \n' % t)
I just don't know, how to execute my function writetime after a certain amount of time elapsed since the last input.
pynput looks like it might be for you. See docs
It would be something like
from pynput import mouse
with mouse.Listener(on_click=reset_timer,
on_move=reset_timer,
on_scroll=reset_timer) as listener:
begin_timer()
Another way might be to set your monitor screen off (screen saver options) after 5 minutes and then write a script which detects the monitor state.
Here is an example on how to do this:
How to check whether the device's display is turned on/off with Python?
Happy coding
It may not be the cleanest solution but since I am a novice Python programmer I am pretty happy with it.
import datetime
from ctypes import Structure, windll, c_uint, sizeof, byref
import time
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
while 1:
GetLastInputInfo = int(get_idle_duration())
if GetLastInputInfo >= 10:
start = time.time()
startTime = datetime.datetime.now()
while GetLastInputInfo >= 10:
GetLastInputInfo = int(get_idle_duration())
if GetLastInputInfo < 10:
end = time.time()
time_elapsed = end - start + 10
if time_elapsed >= 10:
with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'w') as f:
f.write('Pause from ' + str(startTime) + ' to ' + str(
datetime.datetime.now()) + '\nDuration: ' + str(time_elapsed))
For testing purposes, I set the time to be marked as absent to 10 seconds. So if you want to make something similar just make sure to change all the 10's to the wished time in seconds
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can I create a loop that sleeps a random amount of time every X minutes, where X is also a random duration of time?
I also want to be able to specify the upper and lower boundaries of the random durations of both times.
You could try something like this:
import random
from datetime import datetime
from time import sleep
# Randomly select a time between 20 to 30 minutes
# before sleeping.
random_time_duration = random.randint(1200,1800)
# Randomly sleep between 60 to 120 seconds.
sleep_duration = random.randint(60,120)
# This is the start time of of loop used to track
# how much time has passed.
old_time = datetime.now()
while True:
# Check if the randomly selected duration has
# passed before running your code block.
if (datetime.now()-old_time).total_seconds() > random_time_duration:
sleep(sleep_duration)
# Reset all the time variables so the loop works
# again.
random_time_duration = random.randint(1200,1800)
sleep_duration = random.randint(60,120)
old_time = datetime.now()
else:
# Put your code in here.
pass
sleep_time = 50 #time to sleep in seconds
difference = 30
sleep_time = random.randint(sleep_time-difference, sleep_time+difference)
sleep_every = 10 #ammount of time to wait before sleeping in minutes
cur_time = time.time()
while True: #change to your for loop
if time.time() - cur_time >= sleep_time * 60:
time.sleep(sleep_time)
cur_time = time.time()
else:
#your code here
print time.time() - cur_time
can obviously be adapted to a function but this works perfectly
here is a sample code using datetime.now() and timedeltas to calculate the next interval somewhat randomly, this has an advantage over using time.time or similar since that would fail at midnight since the date would also be important in that case:
import time
import random
import datetime
sleep_duration = 1 #seconds
min_sleep_interval = max_sleep_interval = 3 #in seconds
_TIME_TO_SLEEP = datetime.datetime.now()
def maybe_sleep():
#using a singleton class you could avoind using globals
global _TIME_TO_SLEEP
if datetime.datetime.now()>= _TIME_TO_SLEEP:
time.sleep(sleep_duration)
seconds_to_wait = random.randint(min_sleep_interval, max_sleep_interval)
next_delay = datetime.timedelta(seconds= seconds_to_wait)
_TIME_TO_SLEEP = datetime.datetime.now() + next_delay
Then just call maybe_sleep() every iteration and adjust the constants to your liking (maybe make them less constant ;)
As a demo:
for i in range(10000):
maybe_sleep()
print(i)
You can try this :
import datetime
import time
import random
sleep_duration = 60
previous_sleep = datetime.datetime.now()
random_offset = random.randint(-5, 5)
while(True):
delta = (datetime.datetime.now() - previous_sleep).total_seconds()
if delta < 60 * (20 + random_offset):
# Do stuff
time.sleep(1)
continue
else:
previous_sleep = datetime.datetime.now()
random_offset = random.randint(-5, 5)
time.sleep(sleep_duration)
This program would sleep for 60 seconds every 15-25 minutes, depending on the random offset computed.