Get decimal part of floating point number in python

I want my Python2 daemon to wake up and do something exactly on the second.

Is there a better way to get the abbreviated part of a floating point number for a different sleep time:

now = time.time()               #get the current time in a floating point format
left_part = long(now)           #isolate out the integer part
right_part = now - left_part    #now get the decimal part
time.sleep(1 - right_part)      #and sleep for the remaining portion of this second.


Sleep time will vary depending on how much work was done in that second.

Is there a Sleep Before feature that I am not aware of? or, is there a better way to handle this?

I would like my daemon to be as efficient as possible so as not to monopolize too much CPU from other processes.

Thank. Mark.


source to share

2 answers

Use math.modf()


Returns the fractional and integer parts of x. Both results are x-sign and are floats.


>>> from math import modf
>>> modf(3.1234)
(0.12340000000000018, 3.0)





not guaranteed to wake up exactly when you say so, it may be somewhat inaccurate.

To get the part after the decimal place, use the modulus operator ( %


>>> 3.5 % 1



>>> t = time.time()
>>> t
>>> 1 - t % 1


As for the "sleep til", you might be interested in the scheduling module which is built around this idea:



All Articles