Python os.utime() Method

Python os.utime() method is used to update the access and modification times of a specific file or directory. It’s a way to change the timestamps on a file or directory.

This method can set the last access and modification times of a file or directory manually. The actual resolution of timestamps depends on the underlying filesystem.

Syntax

os.utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True)

Parameters

Name Description
path (string) The path to the file or directory.
times (tuple, optional) It is a tuple of two floats, the first representing the access time in seconds and the second representing the modification time in seconds.
ns (tuple, optional) A tuple of two integers.
dir_fd (optional) It is a file descriptor that refers to a directory.
follow_symlinks (optional, boolean) If True, symbolic links are followed, and the timestamps of the file pointed to are changed. If False, the timestamps of the symbolic link itself are changed.

Return values

This method does not return any value.

Example 1: Updating file timestamps

Modification time of a txt file before using the os.utime() method:

Screenshot of file before updating file timestamps

import os
import time

file_path = 'new.txt'
current_time = time.time()

# Update the access and modification times to the current time
os.utime(file_path, (current_time, current_time))

print("Updated the access and modification times to current time")

Output

Updated the access and modification times to current time

Output of Python os.utime() method

Example 2: Updating directory timestamps

Modification time of a “dir” directory before changing it to the current time:

Screenshot of before changing the timestamps of a directory

import os
import time

dir_path = 'dir'
current_time = time.time()

# Update the access and modification times to the current time
os.utime(dir_path, (current_time, current_time))

print("Updated the access and modification times to current time of a directory")

Output

Updated the access and modification times to current time of a directory

Output of changing the modified date time to current time of a directory

Example 3: Setting specific timestamps in nanoseconds

import os
import time

file_path = 'new.txt'
current_time_ns = time.time_ns()

# Update the access and modification times to the current time
os.utime(file_path, ns=(current_time_ns, current_time_ns))

print("Setting a time in nano seconds of a file")

Output

Setting a time in nano seconds of a file

Remember to handle potential errors and permissions issues, especially when working in a multi-user environment or with sensitive system files.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.