Python: Getting the Creation Date of a File/Directory

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

Working with files and directories is a common task for programmers. In Python, various libraries and modules help developers interact with the filesystem. One task that often arises is the need to find out when a file or directory was created. This information can be critical for purposes such as organization, backup systems, or simply for informational purposes.

In this tutorial, we will explore how to use Python to retrieve the creation date of a file or a directory. Before we dive into the code examples, it’s important to understand that the creation date you can access may vary across different operating systems. This is because each file system treats file metadata differently.

On Windows, for example, you can easily access the creation time of files. However, on many Unix-based systems, including macOS and Linux, the ‘creation time’ concept does not directly translate. Typically, Unix filesystems store three main timestamps for each file: the last access time (atime), the last modification time (mtime), and the inode change time (ctime). Some newer filesystems, like APFS on macOS, do store a creation time, but it’s not universally available.

Retrieving Creation Date on Windows

In Windows, we can use the built-in os module which includes the stat function to retrieve file metadata. The ‘st_ctime’ attribute from the metadata represents the creation time.

import os

file = 'example.txt'
file_stats = os.stat(file)
creation_time = file_stats.st_ctime

print("The file was created on:", time.ctime(creation_time))

This code snippet retrieves the creation time of ‘example.txt’ and prints it in a human-readable form.

Retrieving Creation Date on Unix

On Unix systems, while the ‘birth time’ or true creation time isn’t always available through the os module, we can fall back on the file’s last modification time as a proxy in cases where the creation time isn’t important. The following code illustrates:

import os
import time

file = 'example.txt'
file_stats = os.stat(file)
modification_time = file_stats.st_mtime

print("The file was last modified on:", time.ctime(modification_time))

However, if you’re on a system—like macOS with APFS—that supports retrieval of the creation date, you can try using the subprocess to call a shell command like stat.

import subprocess

file = 'example.txt'
command = ['stat', '-f', 'Birth: %SB', file]
process_output = subprocess.run(command, capture_output=True, text=True)

print(process_output.stdout)

This code calls the native stat command, requesting the creation time and then printing it.

Python Libraries for File Metadata

There are also third-party Python libraries that can help with getting more consistent across different file systems. One such library is pathlib, which is a built-in library in Python 3.4 and above that provides an object-oriented interface to the filesystem. With pathlib, we shall attempt to get the birth time of a file.

from pathlib import Path
import time

file_path = Path('example.txt')
creation_time = file_path.stat().st_ctime

print("The file was created on:", time.ctime(creation_time))

Remember that this also returns the st_ctime on Unix, which is not the creation time, but the change time. Use this carefully and always ensure that the date retrieved reflects what’s required based on the system’s semantics.

Error Handling

When working with files, it’s always important to handle potential errors, such as what happens if the file does not exist. Python’s os module will throw a FileNotFoundError.

import os

file = 'example.txt'

try:
    file_stats = os.stat(file)
    creation_time = file_stats.st_ctime
    print("The file was created on:", time.ctime(creation_time))
except FileNotFoundError:
    print("The file does not exist.")

This simple error handling will prevent your program from crashing and provide a user-friendly message when the file specified is not found.

Final Words

Knowing how to get the creation date of files and directories is invaluable in many programming and scriptwriting scenarios. While it’s straightforward on Windows, Unix-based system users must carefully choose the right method to ensure the information they retrieve is accurate for their needs. This tutorial covered how to handle file creation dates and times in Python, discuss the differences across operating systems, and illustrate a few methods and libraries that can be used to retrieve this information.

With Python’s extensive library support, you can integrate file metadata operations seamlessly into your applications, storing, managing, and organizing files efficiently. And with error handling, your application will be robust and less prone to crashing.

Whether you need to query file metadata for system administration tasks, logging, or organizing data, Python provides you the tools to do so successfully. Remember to consider cross-platform compatibility if you’re working in a heterogeneous environment to ensure your code runs smoothly across different systems.

By leveraging these capabilities, Python continues to be a powerful and valuable language for automation, file system analysis, and beyond.