🔍 Code Extractor

function get_file_times

Maturity: 45

Retrieves all available timestamps for a file, including modification time, access time, change time, and birth time (creation time) when available.

File:
/tf/active/vicechatdev/mailsearch/fix_file_dates.py
Lines:
15 - 42
Complexity:
moderate

Purpose

This function provides comprehensive timestamp information for a given file path. It uses os.stat() to retrieve standard timestamps (modified, accessed, changed) and attempts to retrieve the birth time (creation time) using platform-specific methods. On systems with st_birthtime support (macOS, BSD), it uses that attribute directly. On Linux systems, it falls back to using the 'stat' command to retrieve the birth time from the filesystem. This is useful for file auditing, backup systems, forensics, or any application that needs detailed file timestamp information.

Source Code

def get_file_times(filepath):
    """Get all timestamps for a file including birth time"""
    stat_info = os.stat(filepath)
    times = {
        'modified': stat_info.st_mtime,
        'accessed': stat_info.st_atime,
        'changed': stat_info.st_ctime
    }
    
    # Try to get birth time (creation time) if available
    if hasattr(stat_info, 'st_birthtime'):
        times['birth'] = stat_info.st_birthtime
    else:
        # On Linux, use stat command to get birth time from filesystem
        try:
            result = subprocess.run(
                ['stat', '-c', '%W', filepath],
                capture_output=True,
                text=True,
                check=True
            )
            birth_time = result.stdout.strip()
            if birth_time and birth_time != '0':
                times['birth'] = float(birth_time)
        except (subprocess.CalledProcessError, ValueError):
            pass
    
    return times

Parameters

Name Type Default Kind
filepath - - positional_or_keyword

Parameter Details

filepath: String or path-like object representing the path to the file whose timestamps should be retrieved. Can be an absolute or relative path. The file must exist and be accessible by the current user, otherwise os.stat() will raise an exception.

Return Value

Returns a dictionary containing file timestamps as Unix epoch timestamps (float values). Always includes keys 'modified' (st_mtime), 'accessed' (st_atime), and 'changed' (st_ctime). May also include 'birth' key with the file creation time if available on the platform. If birth time cannot be determined, the 'birth' key will be absent from the dictionary. All timestamp values are in seconds since the Unix epoch (January 1, 1970).

Dependencies

  • os
  • subprocess

Required Imports

import os
import subprocess

Usage Example

import os
import subprocess
from datetime import datetime

def get_file_times(filepath):
    stat_info = os.stat(filepath)
    times = {
        'modified': stat_info.st_mtime,
        'accessed': stat_info.st_atime,
        'changed': stat_info.st_ctime
    }
    if hasattr(stat_info, 'st_birthtime'):
        times['birth'] = stat_info.st_birthtime
    else:
        try:
            result = subprocess.run(
                ['stat', '-c', '%W', filepath],
                capture_output=True,
                text=True,
                check=True
            )
            birth_time = result.stdout.strip()
            if birth_time and birth_time != '0':
                times['birth'] = float(birth_time)
        except (subprocess.CalledProcessError, ValueError):
            pass
    return times

# Example usage
filepath = '/path/to/your/file.txt'
times = get_file_times(filepath)

print(f"Modified: {datetime.fromtimestamp(times['modified'])}")
print(f"Accessed: {datetime.fromtimestamp(times['accessed'])}")
print(f"Changed: {datetime.fromtimestamp(times['changed'])}")
if 'birth' in times:
    print(f"Birth: {datetime.fromtimestamp(times['birth'])}")
else:
    print("Birth time not available")

Best Practices

  • Always check if 'birth' key exists in the returned dictionary before accessing it, as it may not be available on all platforms or filesystems
  • Handle potential OSError or FileNotFoundError exceptions when calling this function with invalid or inaccessible file paths
  • Be aware that on Linux, birth time is only available on certain filesystems (btrfs, ext4 with kernel 4.11+) and may return 0 or be unavailable on older systems
  • The 'changed' time (st_ctime) represents metadata change time on Unix/Linux, not creation time
  • Consider wrapping the function call in a try-except block to handle cases where the file doesn't exist or permissions are insufficient
  • The subprocess call to 'stat' command may fail on Windows systems; this function is designed primarily for Unix-like systems
  • Timestamp values are in seconds since Unix epoch; use datetime.fromtimestamp() to convert to human-readable format

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function set_file_dates 64.8% similar

    Sets all file timestamps (creation time, modification time, access time, and change time) to a specified Unix timestamp by directly modifying the file's inode using debugfs.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
  • function fix_file_dates 57.1% similar

    Normalizes all timestamp attributes (creation, modification, access) of a file to the oldest timestamp among them, with optional dry-run mode for preview.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
  • function get_file_version 54.7% similar

    Generates a version string for static files to enable cache busting, using current time in debug mode or file modification time in production.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function copy_file_with_date 52.8% similar

    Copies a file from source to destination and sets the file's modification and access times to match a provided datetime object.

    From: /tf/active/vicechatdev/mailsearch/copy_signed_documents.py
  • function get_file_version_v1 51.3% similar

    Generates a version string for static files based on their modification time, used for cache busting in web applications.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse