DePianoman DePianoman - 1 month ago 8
Python Question

Pygame datetime troubles

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?

Answer

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)