Python os.utime() Method
os.utime() Overview
The os.utime() method is used to set the last modified and accessed time of the specified path file.
Valid in Unix, Windows.
os.utime() Syntax
The utime() method syntax format is as follows.
os.utime(path, times)
os.utime() Parameters
- path – the path to the file
- times – If the time is None, then the file access and modification is set to the current time. Otherwise, the time is a 2-tuple number, (atime, mtime) used as the time of access and modification respectively.
os.utime() Return Value
This method has no return value.
os.utime() Example#1
The following example demonstrates the use of the utime() method.
Set the access time and modification time for the specified path using os.utime() method
Either we can specify times or specify ns parameter. It is an error to specify tuples for both times and ns.
import os
path = '/root/apidemos.com.txt'
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
atime = 200000000
mtime = 100000000
tup = (atime, mtime)
os.utime(path, tup)
print("Access and modification time changed to ", path)
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
Output:
os.utime() Example#2
Set the access time and modification time in nanoseconds for the above specified path using os.utime() method (ns is keyword only argument).
Either we can specify times or specify ns parameter. It is an error to specify tuples for both times and ns.
import os
path = '/root/apidemos.com.txt'
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
atime_ns = 20000000012345
mtime_ns = 10000000012345
tup = (atime_ns, mtime_ns)
os.utime(path, ns = tup)
print("Access and modification time changed for ", path)
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
Output:
os.utime() Example#3
If times is None and ns is unspecified, then it will be equivalent to specifying ns = (atime_ns, mtime_ns) where member atime_ns and mtime_ns are current time in nanoseconds.
import os
path = '/root/apidemos.com.txt'
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
os.utime(path)
print("\nAccess and modification time changed\n")
print("Current access time by os.stat(path).st_atime:", os.stat(path).st_atime)
print("Current modification time by os.stat(path).st_mtime:", os.stat(path).st_mtime)
Output: