Python — file modification time perils

Author:Wojciech Muła
Added on:2018-11-24

I need to copy a file to another directory whenever it got changed. The easiest way to do this is to check the modification time of file, a number of seconds since epoch:

import os
def get_mtime(path)
    return os.stat(path).st_mtime

It's not the most reliable way, but in my case it was good enough. Up to the time when I noticed that sometimes files didn't get updated.

I figured out that for a reason get_mtime returned an integer value, while the file system was able to deal with higher resolution than a second; system command stat printed microseconds.

The culprit was the setting of os module. It is possible to select in runtime, by os.stat_float_times(boolean), whether the module reports times as integers or floats. For an unknown reason my python installation defaulted to integers. Thus it was possible to have two files with different modification times having the same integer parts.

Finally, I forced float times everywhere (os.stat_float_times(True)).