lizzie
lizzie

Reputation: 1656

simulate time python

I want to simulate time in Python. I want to apply "my_fct" every second, however I do not know how long "my_fct" takes to run so I cannot use a sleep. What I did is this:

    past_time =  datetime.datetime.utcnow()
    present_time =  datetime.datetime.utcnow()
    for i in range(10):
        while( (present_time - past_time).total_seconds()  < 1):
            present_time = datetime.datetime.utcnow()
        my_fct(......)
        past_time = present_time

I don't think it is the good way to do it? What is the right solution? Thank you

Upvotes: 4

Views: 5571

Answers (1)

Inbar Rose
Inbar Rose

Reputation: 43437

running your code gives:

>>> 

Traceback (most recent call last):
  File "C:\python\tester.py", line 6, in <module>
    while((present_time - past_time) < 1):
TypeError: can't compare datetime.timedelta to int

what you need is this:

import datetime

past_time =  datetime.datetime.utcnow()
present_time =  datetime.datetime.utcnow()
for i in range(10):
    while((present_time - past_time).seconds < 1):
        present_time = datetime.datetime.utcnow()
    my_fct(......)
    past_time = present_time

time-time gives a timedelta value. u need the seconds of this value. and then compare to your int.

edit: however, i now realize this is not the solution you are looking for.

this is a way to do it with threads (a very simple way - prone to problems depending on what my_fct() does.)

import time
from threading import Thread

 for i in range(10):
    time.sleep(1)
    t = Thread(target=my_fnc, args=(......))
    t.start()

Upvotes: 7

Related Questions