What I am trying to accomplish is first text appears after 1 second. then 2, ect. till 10. then when time equals 10, the time decreases, so the text appears after 9 seconds, then 8 etc.
How could I fix this code so that it works properly?
The error:
Traceback (most recent call last):
File "C:/Users/Eric/Dropbox/time.py", line 13, in <module>
time.sleep(time)
AttributeError: 'int' object has no attribute 'sleep'
The code :
import time
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >=10:
time = t - 1
elif time <= 0:
time = t + 1
time.sleep(time)
Edit:
import time
x = 1
t = 1
time1 = 0
while x == 1:
if time1 == 10:
time1 = time1 - 1
elif time1 == 0:
time1 = time1 + 1
else :
time1 = time1 + 1
print time1
time.sleep(time1)
So I changed the program around abit, so I almost works correctly. What it does is count to 10, then 9 then back to 10.
ex. 1,2,3,4,5,6,7,8,9,10,9,10,9,10
how can I set it so that the program increases time to ten then decreases to zero then increases again?
You're overriding the imported time module (line 1) by your own time variable (line 4). You can:
rename your time variable to something else
import time
x = 1
t = 1
time_passed = t + 1 # use "time_passed" instead of "time" for example
while x == 1:
print time_passed
if time_passed >= 10:
time_passed = t - 1
elif time_passed <= 0:
time_passed = t + 1
time.sleep(time_passed)
alias the imported time module with import time as tm the use tm.sleep(time)
import time as tm # alias the time module as "tm" for example
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
tm.sleep(time) # use "tm" to refer to the module
only import sleep from time with from time import sleep and use sleep(time) instead
from time import sleep # only import "sleep" from time, not the whole module
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
sleep(time) # use "sleep" directly
After fixing this, you also need to somehow remember that you need to either increase or decrease the time at the next iteration. For example:
from time import sleep
x = 1
t = 1
time = t + 1
incr = True
while x == 1:
print time
if time >= 10:
time = 9
incr = False
elif time <= 0:
time = t + 1
incr = True
else:
if incr:
time = time + 1
else:
time = time - 1
sleep(time)
You're redefining 'time' after you import it...
Try using a different variable name.
Your time variable is conflicting with the module (time) that you imported. You could use curTime or myTime instead as your variable name.
Related
I tried these codes.
x = 6
while 1:
if x < 0.999:
break
#execute you function after 6 seconds.
x -= 0.01
sleep(0.01)
But i need to execute on a particular time . So i tried this:
if (self.is_hour_between("09:55:00", "11:20:00")) == True:
#your function
else:
#your function
def time_between(self, start, end):
# Time Now
now = datetime.now().time()
# Format the datetime string
time_format = "%H:%M:%S"
# Convert the start and end datetime to just time
start = datetime.strptime(start, time_format).time()
end = datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
i wanted to run the function at exactly 10 Am and 11Am .If its not the time then wait for it.else if its the time then go for it without waiting
Anwser :
import datetime
import time
while True:
current_dt = datetime.datetime.now()
time_a = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 9, 55)
time_b = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 11, 20)
if (time_a<current_dt) and (time_b > current_dt):
print('ok')
else:
time.sleep(60)
I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules.
The keyboard module from PyPi.
Everything works as expected, and I am able to press a button to close the program, but it only works at the beginning of each iteration. Is there a way for it to check for a key press at any point while the loop is running? Do I need to be using a different module?
This is my code:
import time
import keyboard
m = 2
s = 0
count_down = True
while True:
if keyboard.is_pressed('q'):
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
Using callback is common approach in such case, here is solution:
import time
import keyboard
m = 2
s = 0
count_down = True
break_loop_flag = False
def handle_q_button():
print('q pressed')
global break_loop_flag
break_loop_flag = True
keyboard.add_hotkey('q', handle_q_button)
while True:
if break_loop_flag:
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1q
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
If you want to do any two things in parallel, independently of another, you need to consider using multiprocessing. However, even if you do, your loop will either still need to check if a key has been registered in the other process, or you need to terminate the process running the loop forcefully, which may result in unexpected outcomes.
However, in your case, since there are no side effects like files being written, this would work:
import time
import keyboard
from multiprocessing import Process
def print_loop():
m = 2
s = 0
count_down = True
while True:
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
def main():
p = Process(target=print_loop)
p.start()
# this loop runs truly in parallel with the print loop, constantly checking
while True:
if keyboard.is_pressed('q'):
break
# force the print loop to stop immediately, without finishing the current iteration
p.kill()
if __name__ == '__main__':
main()
I am trying to create a little game with python. I already set everything but I would like to set a time limit. I found something on the internet but it is not working with this project but it works with another project.
c.create_text(450, 20, text = 'Time', fill = 'red')
c.create_text(650, 20, text = 'Score', fill = 'red')
time_text = c.create_text(450, 20, text = 'Time', fill = 'red')
score_text = c.create_text(650, 20, text = 'Score', fill = 'red')
def print_score(score) :
c.itemconfig(score_text, text = str(score))
def print_time(time) :
c.itemconfig(time_text, text = str(time))
ENNEMY_CHANCE = 10
TIME_LIMIT = 30
SCORE_BONUS = 1000
score = 0
bonus = 0
end = time() + TIME_LIMIT
#Main
while True :
if randint(1, ENNEMY_CHANCE) == 1:
create_ennemy()
move_ennemies()
hide_ennemies()
score += ennemy_kill()
if(int(score/SCORE_BONUS)) > bonus:
bonus += 1
end += TIME_LIMIT
print_score(score)
print_time(int(end - time()))
window.update()
But I get this:
end = time() + TIME_LIMIT
TypeError: 'int' object is not callable
If you know an easier way to set a time limit that would be super.
Did you import time? I think you used the "time" name as an integer variable somewhere in your code and you have ambiguous code. Try this to get current time:
import time as time_module
now = time_module.time()
Try this
import time
start = time.time() #the variable that holds the starting time
elapsed = 0 #the variable that holds the number of seconds elapsed.
while elapsed < 30: #while less than 30 seconds have elapsed
elapsed = time.time() - start #update the time elapsed
This question already has answers here:
Python: pop from empty list
(5 answers)
Closed 3 years ago.
I was experimenting with some datetime code in python so I could do a time.sleep like function on one piece of code, while letting other code run.
Here is my code:
import datetime, pygame
pygame.init()
secondtick = pygame.time.Clock()
timestr = str(datetime.datetime.now().time())
timelist = list(timestr)
timex = 1
while timex <= 6:
timelist.pop(0)
timex += 1
timex2 = 1
while timex2 <= 7:
timelist.pop(2)
timex2 += 1
secondstr1 = str("".join(timelist))
while 1:
timestr = str(datetime.datetime.now().time())
timelist = list(timestr)
timex = 1
while timex <= 6:
timelist.pop(0)
timex += 1
timex2 = 1
while timex2 <= 7:
timelist.pop(2)
timex2 += 1
secondstr2 = str("".join(timelist))
x = 1
if int(secondstr2) - x == int(secondstr1):
print(x)
x += 1
and here is the result:
C:\Python32\python.exe "C:/Users/depia/PycharmProjects/testing/test.py"
Traceback (most recent call last):
File "C:/Users/depia/PycharmProjects/testing/test.py", line 31, in <module>
timelist.pop(2)
IndexError: pop index out of range
Process finished with exit code 1
If I add a time.sleep(1) after importing time right here:
-- code --
time.sleep(1)
secondstr2 = str("".join(timelist))
-- more code --
this is the output:
C:\Python32\python.exe "C:/Users/depia/PycharmProjects/testing/test.py"
1
then it never ends. It just stays like that forever. Can anyone help?
You can use pygame.time.get_ticks to control time.
To delay your event for 1 second (1000ms) first you set
end_time = pygame.time.get_ticks() + 1000
and later in loop you check
if pygame.time.get_ticks() >= end_time:
do_something()
or even (to repeat it every 1000ms)
if pygame.time.get_ticks() >= end_time:
do_something()
end_time = pygame.time.get_ticks() + 1000
#end_time = end_time + 1000
It is very popular method to control times for many different elements in the same loop.
Or you can use pygame.time.set_timer() to create own event every 1000ms.
First set
pygame.time.set_timer(pygame.USEREVENT+1, 1000)
and later in loop you check
for event in pygame.event.get():
if event.type == pygame.USEREVENT+1:
do_something()
It is useful if you have to do something periodicaly
BTW: use 0 to turn off event
pygame.time.set_timer(pygame.USEREVENT+1, 0)
So I have this here.
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours = 2
if Hours == 12:
Hours = 1
Minutes = 0
break
ReadLine = ("\t{0:>2} : {1:>2}\r").format(Hours, Minutes)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
Just for the record, I have made sure that the indentations are correct, they look a little screwy here. And I realize that I have nothing set for A.M./P.M. as of yet.. Any help is appreciated for this noob.
Thank you - Matt.
Edit:
>>> 2: 0 2: 0 2: 0
This is what is printing out now, the minutes have not updated. I'm obviously missing something. Once again thanks for any help, and I am sorry if this is a repeat, I have searched for an answer, but none was found. Thanks - Matt.
Edit #2- I figured it out. I used a bit of both of the answers, and whilst I accept the fact that it will be slow it does what I want it to do.
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
AM_PM = "AM" if Hours < 12 else "P.M"
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours += 1
if Hours == 24:
Hours = 1
Minutes = 0
break
ReadLine = ("\t{:>2} : {:>2} {}\r").format(Hours, Minutes, AM_PM)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
You know, it seems no matter how hard I try, I cannot get this darned indentation to look right. Oh well, I hope you can understand it's just tabbed a bit to the right.
your code print nothing because you put the code that print to stdout inside the if statements. so it would print only when Minutes == 60 and Hours == 12 (which will never happend because of you dont increament Hours as meantioned in the comments.
try this:
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
ampm = "AM"
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours += 1
if Hours == 12:
Hours = 1
Minutes = 0
ampm = ("AM" if (ampm == "PM") else "PM")
ReadLine = ("\t{0:>2} : {1:>2} {2} \r").format(Hours, Minutes,ampm)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
import datetime
then = now = datetime.datetime.now()
minutes = 0
hours = 0
while True:
now = datetime.datetime.now()
if (now-then).total_seconds() > 60:
then += datetime.timedelta(minutes=1)
minutes += 1
if minutes == 60:
minutes = 0
hours += 1
if hours == 24:
hours = 0
am_pm = "AM" if hours < 12 else "PM"
print("{:>2}:{:>02} {}".format((hours+11)%12+1, minutes, am_pm))
Note that I do away with time.sleep as it's not guaranteed to sleep for exactly the time requested (indeed you will always be running slightly slow by that clock) and instead compare a current time to the last time a minute passed and see if the total seconds are more than 60. If so, increment minutes, if minutes is 60, increment hours and check for rollover and am_pm switch. Afterwards, print the time.
If you're wanting to stretch your legs a little, try implementing it in a class! Ooh ooh, and threading too!
import datetime
import threading
import queue
class Clock(object):
def __init__(self, current_time=None):
if isinstance(current_time, datetime.datetime):
hours, minutes = current_time.hour, current_time.minute
else:
hours = minutes = 0
self.hours = hours
self.minutes = minutes
self.q = queue.Queue()
def checkTime(self):
try:
self.q.get_nowait() # time has updated, or exception thrown
self.updateTime()
self.q.task_done()
except queue.Empty:
pass # time hasn't updated
def updateTime(self, num_mins=1):
self.minutes += 1
if self.minutes == 60:
self.minutes = 0
self.hours += 1
if self.hours == 24:
self.hours = 0
print(self)
def minutePassed(self):
then = datetime.datetime.now()
while True:
now = datetime.datetime.now()
if (now-then).total_seconds() > 60:
then += datetime.timedelta(minutes=1)
self.q.put('_') # put something there, doesn't matter what
def __str__(self):
am_pm = "AM" if self.hours < 12 else "PM"
return "{:>2}:{:>02} {}".format((self.hours+11)%12+1,
self.minutes, am_pm)
def start(self):
t = threading.Thread(target=self.minutePassed)
t.daemon=True
t.start()
while True:
self.checkTime()
clock = Clock(datetime.datetime.now())
clock.start()