Modify atime and mtime of a file on Linux with nanosecond precision

Hello!
On Linux, the stat command offers nanosecond precision when showing atime and mtime:

$ stat /tmp/file1 
  File: /tmp/file1
  Size: 7         	Blocks: 8          IO Block: 4096   regular file
...
Access: 2025-05-24 12:04:26.946841260 +0200
Modify: 2025-05-24 12:04:26.946841260 +0200
Change: 2025-05-24 12:04:26.946841260 +0200
 Birth: 2025-05-24 12:04:26.946841260 +0200

With Python 3.10, I can get those times with the same precision:

>>> os.stat("/tmp/file1").st_mtime_ns
1748081066946841260
>>> os.stat("/tmp/file1").st_atime_ns
1748081066946841260

I would also like to set them.

touch may be used with -d to accomplish this, as suggested here. If this is the only way also from Python, how to obtain a time of the form 2025-05-01 01:01:01.123456789?

Or is there another way to set them directly through Python, without running touch?

os.utime (update time) is the function you are locking for; it has an ns keyword parameter for this purpose.

1 Like

Thank you!
I just write an example, if it can be useful:

new_atime = os.stat("/path/to/file_A").st_atime_ns
new_mtime = os.stat("/path/to/file_A").st_mtime_ns
os.utime("/path/to/file_B", ns=(new_atime, new_mtime))

This will update atime and mtime of file_B with the atime and mtime of file_A, with nanosecond precision.

Here the official documentation.