My 'if int(time.time()) % 2 == 0:' doesn't always print out even sec

1a2*_*a6a 0 python

start = int(time.time())

while True:  

    if int(time.time()) % 2 == 0:
        img = ImageGrab.grab()
        saveas = 'screenshot' + str(int(time.time())) + '.png'
        img.save(saveas)

    elif start + 30 == int(time.time()):
        break
Run Code Online (Sandbox Code Playgroud)

result : https://i.stack.imgur.com/Aqdv6.png

Hi guys. It's a simple code but not working accurately. I wanted to save a screenshot of my screen for every 2 seconds. but in the result, I have some of those odd second files like 'screenshot1552893309.png'. What should I do to fix it?

Tae*_*ung 5

This happens because "time flies."

You are calling time.time() at most three times per iteration of the while loop.

Each call of time.time() returns the UNIX time at the given call. In your code, each call can be invoked at different seconds (thus returning different timestamps.)

For example, consider this situation: time.time() from if int(time.time()) % 2 == 0: returns 1552893308.0, so the condition is satisfied, but the next call returns 1552893309.0, which will leave its trace to the file name.

Instead, you might want to call time.time() only once per iteration, and then do what you want with that timestamp.

start = int(time.time())

while True:  
    current_time = int(time.time())
    if current_time % 2 == 0:
        img = ImageGrab.grab()
        saveas = 'screenshot' + str(current_time) + '.png'
        # or you can also say
        # saveas = f'screenshot{current_time}.png'
        img.save(saveas)

    elif start + 30 <= current_time:
        break
Run Code Online (Sandbox Code Playgroud)

Note the change of the boolean operator in elif. start + 30 == current_time seems too vulnerable to making a infinite loop.

Also note the commented use of f-strings, which was introduced in Python 3.6