os.path.getmtime() inconsistent with time.time()

79 Views Asked by At

I'm trying to verify the time of most recent modification of a file and got to the following:

    print("before", time.time())
    with open(file, "wb") as fh:
        fh.write(b"12345")
    print("after", time.time())
    print("modified", os.path.getmtime(file))

I expect before < modified < after. But the output reads:

before   1693392599.8838775
after    1693392599.8839073
modified 1693392599.8792782

What am I missing? Thank you.

1

There are 1 best solutions below

1
Jan Morawiec On

The python documentation says the following about the precision of timestamps returned by time.time():

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

I presume getmtime() just reads the file's metadata, so if time.time() is not precise enough it could explain the slight discrepancy in timestamps. What an interesting find.