[파이썬] os 파일의 수정 시간 확인: `os.path.getmtime()`

Syntax of os.path.getmtime()

import os

modification_time = os.path.getmtime(path)

The os.path.getmtime() function takes a single argument, path, which represents the file path you want to check. It returns the time of the most recent modification of the file in the form of a timestamp.

Example Usage

Let’s say we have a file named ‘example.txt’ and we want to check its modification time.

import os

file_path = 'example.txt'
modification_time = os.path.getmtime(file_path)
print(f"The modification time of '{file_path}' is: {modification_time}")

Output:

The modification time of 'example.txt' is: 1635482301.8871057

As you can see, the os.path.getmtime() function returns the time in seconds since the epoch (January 1, 1970). This timestamp represents the last modification time of the file ‘example.txt’.

Converting Timestamp to Readable Format

While the timestamp returned by os.path.getmtime() is useful for comparison or calculations, it is often more convenient to convert it to a readable format. To achieve this, we can use the datetime module.

import os
from datetime import datetime

file_path = 'example.txt'
modification_time = os.path.getmtime(file_path)
modification_time_readable = datetime.fromtimestamp(modification_time)

print(f"The modification time of '{file_path}' in a readable format is: {modification_time_readable}")

Output:

The modification time of 'example.txt' in a readable format is: 2021-10-29 09:05:43

The datetime.fromtimestamp() function converts the timestamp to a datetime object, which can then be formatted and printed in a more user-friendly manner.

That’s it! Now you have a basic understanding of how to use os.path.getmtime() to check the modification time of a file in Python. This function comes in handy when working with file synchronization, log files, or any scenario where tracking file changes is required. Feel free to explore further and incorporate this functionality into your own Python projects.