How do I get file creation and modification date/times in Python?

To retrieve a file’s creation and modification timestamps in Python, you can use the os or pathlib modules. However, creation time (ctime) behaves differently across operating systems. Here’s how to do it:

1. Using os Module

import os
from datetime import datetime

file_path = "example.txt"

# Get timestamps (in seconds since epoch)
mod_time = os.path.getmtime(file_path)  # Last modification time
create_time = os.path.getctime(file_path)  # Creation time (OS-dependent)
access_time = os.path.getatime(file_path)  # Last access time

# Convert to readable datetime objects
mod_dt = datetime.fromtimestamp(mod_time)
create_dt = datetime.fromtimestamp(create_time)

print(f"Modified: {mod_dt}")
print(f"Created (ctime): {create_dt}")

2. Using pathlib (Python 3.4+)

from pathlib import Path
from datetime import datetime

file = Path("example.txt")
stat = file.stat()

mod_time = stat.st_mtime  # Modification time
create_time = stat.st_ctime  # "Creation" time (OS-dependent)

print(f"Modified: {datetime.fromtimestamp(mod_time)}")
print(f"Created (ctime): {datetime.fromtimestamp(create_time)}")

Key Notes

  • st_ctime (Creation Time):
  • Windows: Actual file creation time.
  • Unix/macOS: Last metadata change time (not creation time).
  • For true creation time on macOS, use stat.st_birthtime: if hasattr(stat, 'st_birthtime'): create_time = stat.st_birthtime # macOS creation time
  • Cross-Platform Example:
  def get_file_times(path):
      stat = os.stat(path)
      times = {
          'modified': stat.st_mtime,
          'created': stat.st_ctime,  # Use st_birthtime for macOS creation
      }
      # Check for macOS creation time
      if hasattr(stat, 'st_birthtime'):
          times['created'] = stat.st_birthtime
      return {k: datetime.fromtimestamp(v) for k, v in times.items()}

Output Formatting

Format timestamps as strings:

datetime.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M:%S")
# Output: '2023-10-05 14:30:45'

Platform-Specific Behavior

OSst_ctimest_birthtime (macOS)
WindowsFile creation timeNot available
LinuxLast metadata change timeNot available
macOSLast metadata change timeActual creation time (✓)

Summary

  • Use st_mtime for last modification time (consistent across OS).
  • Use st_ctime cautiously (OS-dependent meaning).
  • For true creation time on macOS, use st_birthtime.

Leave a Reply

Your email address will not be published. Required fields are marked *