DRINK
DRINK

Reputation: 452

Time addition in python

i simplify my code:

print "hello"

# BeginTime is time in this moment e.g. 9h 45m 23s
# timeplus10s is time 9h 45m 33s

while BeginTime < timeplus10s:
    print "i'm doing something"
print "hello after 10 seconds"

as you can see i wanna create construction in while cycle that will last for 10 seconds.

I can't use time.sleep() because I need to do something (which you can' t see because it's simplified).

How can i do that?

Upvotes: 0

Views: 141

Answers (3)

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

from time import time

print "hello"

end_time = time() + 10
while time() < end_time:
    print "i'm doing something"

print "hello after 10 seconds"

Upvotes: 0

Adalee
Adalee

Reputation: 538

import time

print "hello"

# BeginTime is time in this moment e.g. 9h 45m 23s
# timeplus10s is time 9h 45m 33s

BeginTime = time.time()
timeplus10s = BeginTime + 10
while BeginTime < timeplus10s:
    BeginTime = time.time()
    print "i'm doing something"

print "hello after 10 seconds"

worked for me. Basically, you only need to save the current time and then check how it changed and if it changed the amount you want, you are done.

Upvotes: 1

felipsmartins
felipsmartins

Reputation: 13549

It sounds that a task executing during on time frame, try it out:

import datetime as d

def task():
    print "I'm doing something!"

#10 seconds from now
END_TIME = d.datetime.now() + d.timedelta(seconds=10)

while d.datetime.now() < END_TIME:
    task()

print "hello after 10 seconds"

Upvotes: 2

Related Questions