Get File Creation and Modification Date in Python

Get File Creation and Modification Date in Python to support various real-world applications that depend on file metadata. Whether you’re managing a large file system, organizing automated backups, or conducting data audits, knowing when a file was created or last modified provides critical context. This information helps ensure accuracy, compliance, and efficiency in both personal and professional environments.

Python makes it incredibly simple to retrieve such metadata. With built-in modules like os and pathlib, you can extract file timestamps across different platforms with just a few lines of code. This blog will guide you through understanding and using these tools effectively.

Understanding File Timestamps

When dealing with files in Python, there are three primary types of timestamps:

  • Creation Time: Indicates when the file was first created. Note that on some Unix systems, this value may not be available.
  • Modification Time: Represents the last time the contents of the file were changed.
  • Access Time: Shows when the file was last opened or read.

Each of these timestamps can be retrieved and interpreted using Python’s standard libraries, making it easier to manage file history and track changes over time.

Python Program to Get File Creation and Modification Date Using OS

# Python Program to Get File Creation and Modification Date Using OS
 
# importing os and time module
import os.path, time

file = pathlib.Path('test.py')
print("Last modification time: %s" % time.ctime(os.path.getmtime(file)))
print("Last metadata change time or path creation time: %s"%time.ctime(os.path.getctime(file)))

Output:

Last modification time: Tue Apr 18 10:43:24 2023
Last metadata change time or path creation time: Tue Apr 18 10:43:24 2023

Python Program to Get File Creation and Modification Date Using stat()

# Python Program to Get File Creation and Modification Date
 
# importing datetime and pathlib module
import datetime
import pathlib

fname = pathlib.Path('file.py')

print("Last modification time: %s" % datetime.datetime.fromtimestamp(fname.stat().st_mtime))

print("Last metadata change time or path creation time: %s" % datetime.datetime.fromtimestamp(fname.stat().st_ctime))

Output:

Last modification time: 2023-04-15 10:43:24.234189
Last metadata change time or path creation time: 2023-04-15 10:43:24.234189

Practical Examples of Get File Creation and Modification Date in Python

Let’s explore how to work with file timestamps using Python.

1. List All Files with Creation and Modification Dates

import os
from datetime import datetime

directory = "./" # Replace with your target directory

for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
creation_time = os.path.getctime(filepath)
modification_time = os.path.getmtime(filepath)
print(f"{filename} - Created: {datetime.fromtimestamp(creation_time)} - Modified: {datetime.fromtimestamp(modification_time)}")

2. Sort Files by Modification Time

files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
files.sort(key=lambda x: os.path.getmtime(os.path.join(directory, x)))

print("Files sorted by modification time:")
for file in files:
print(file)

3. Filter Files Modified Within a Specific Date Range

from datetime import datetime

start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 12, 31)

for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
mod_time = datetime.fromtimestamp(os.path.getmtime(filepath))
if start_date <= mod_time <= end_date:
print(f"{filename} - Modified on: {mod_time}")

Retrieving file creation and modification dates using Python is vital in real-life applications like automated backups, file version tracking, and audit trails. For example, developers can identify outdated log files for cleanup, while system administrators can monitor unauthorized file changes. In data analysis, timestamps help in organizing records chronologically. Media management tools use this metadata to sort photos or videos by date. Python’s os and pathlib modules make it easy to automate these tasks, improving efficiency and accuracy in file handling. This functionality is especially useful in large-scale environments where manual tracking is impractical.

Common Pitfalls and Tips for Get File Creation and Modification Date in Python

Always Test for Compatibility: Since timestamp behavior may vary across file systems and OS versions, it’s best to test your script thoroughly in the actual deployment environment.

Platform Differences in ctime: On Windows, os.path.getctime() returns the file creation time. On Unix-based systems, it returns the time of the last metadata change—not the creation time. Always test on your target OS.

File Access Exceptions: Your script may throw errors if files are missing or you lack permission to access them. Wrap file access logic in try-except blocks for safe execution.

In conclusion, retrieving file creation and modification dates in Python is essential for efficient file management, backups, and audits. By leveraging Python’s built-in libraries like os and pathlib, users can automate these tasks with ease. Explore more tools and tutorials at Newtum to enhance your Python skills.

About The Author

Leave a Reply