Q: finding distance between 2 time's

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat May 30 10:10:29 EDT 2009


On Sat, 30 May 2009 12:06:55 +0200, jkv wrote:

> I added a few lines to your script, and now it ought to only print files
> newer than 3601 seconds (3600 seconds is one hour). 
...
>     #if file newer than one hour print a line 
>     if time_difference < 3601:

That's a potential off-by-one error. That may print files that are older 
than one hour. Admittedly, they'll be off by less than one second, but if 
you're going to write code, write correct code. The right test is:

    if time_difference <= 3600:

(and you may even want to deal with files that have a *negative* time 
difference, e.g. they were created apparently in the future).

This is particularly necessary if you use time.time() to generate the 
current time, since that returns fractions of a second. But even if you 
don't, it's still the right thing to do: it's defensive programming. 
Rather than assume that all file systems store timestamps accurate only 
to a second, assume that some file system, somewhere, will be accurate to 
fractions of a second, and code accordingly.

That way, no matter what the file system does, your code will still do 
the right thing, and (in this case) it doesn't even cost you anything.



-- 
Steven



More information about the Python-list mailing list