function get_file_times
Retrieves all available timestamps for a file, including modification time, access time, change time, and birth time (creation time) when available.
/tf/active/vicechatdev/mailsearch/fix_file_dates.py
15 - 42
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
ossubprocess
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function set_file_dates 64.8% similar
-
function fix_file_dates 57.1% similar
-
function get_file_version 54.7% similar
-
function copy_file_with_date 52.8% similar
-
function get_file_version_v1 51.3% similar