views:

144

answers:

2

Hello guys, I've an application where, for testing, I need to replace the time.time() call with a specific timestamp, I've done that in the past using ruby

(code available here: http://github.com/zemariamm/Back-to-Future/blob/master/back_to_future.rb )

However I do not know how to do this using Python.

Any hints ? Cheers, Ze Maria

+12  A: 

You can simply set time.time to point to your new time function, like this:

import time

def my_time():
    return 0.0

old_time = time.time
time.time = my_time
Daniel Stutzbach
+2  A: 

By the way, don't ever let code like that escape your test environment. That is absolutely not the Python way of doing things and will incur the wrath of other programmers who suddenly realize why their time-based calculations are mysteriously broken.

Just Some Guy
This should be a comment -- it doesn't answer the question.
cdleary
But there are valid reasons to patch time.time and alikes: datetime.timedelta, for instance has no ability to be divided by floats, or other timedeltas even though both of these operations make sense. td/td is a ratio, and we have to write helper methods to handle this. Patching td to allow this would make for much cleaner end user code.
Matthew Schinckel
I disagree. You can always subclass timedelta into something like timedeltawithfloats and use that in your code. That approach guarantees that timedelta will work exactly as expected by other modules that use it.
Just Some Guy