Explain Codes LogoExplain Codes Logo

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

python
file-handling
timestamp
pathlib
Alex KataevbyAlex Kataev·Oct 22, 2024
TLDR

Here's a quick recipe to fetch the creation and modification dates of a file in Python. We'll use os.path.getmtime() for the last modified date and pathlib.Path().stat().st_ctime for the creation date:

import os from pathlib import Path from datetime import datetime file_path = 'your_file.txt' # Add your file path here # Modification time mod_time_epoch = os.path.getmtime(file_path) print(f"Modified on: {datetime.fromtimestamp(mod_time_epoch)} # No, the file didn't time travel, but it sure felt like it did.") # Creation time (OS-dependent) create_time_epoch = Path(file_path).stat().st_ctime print(f"Created on: {datetime.fromtimestamp(create_time_epoch)} # Yeah, your file has a birthday. Let's celebrate!")

This will give you readable modification and creation dates directly. Straightforward and neat! Just note that the creation time is handled differently depending on the operating system.

Digging into file timestamps

Files keep track of their historical metadata, somewhat like a person's diary. So, when you sort documents or verify compliance, knowing a file's creation and modification dates becomes imperative.

Handling differences across platforms

Windows and Unix-ish systems (including Linux and macOS) have different ways of time-keeping birthing and aging of files. Consider these nuances when fetching timestamps:

  • Windows: os.path.getctime() got your back for file creation time.
  • macOS/Unix: os.stat().st_birthtime will get you the birth date of a file.
  • Linux: Notoriously, it doesn't keep track of file birth times - we know, right? But you can use os.stat().st_mtime as a close substitute.

For cross-platform code, you'll need to use platform.system() to find out the OS and then decide which method to use. Clever, huh?

Making timestamps human-friendly

Epoch timestamps aren't exactly easy on human eyes, but we can tame them using datetime.fromtimestamp() or time.ctime():

print(f"Human-friendly creation time: {time.ctime(create_time_epoch)}") # Now we're talking!

Want to make your timestamp look stylish? Python's strftime method can help you customize the format:

print(f"Created on: {datetime.fromtimestamp(create_time_epoch).strftime('%Y-%m-%d %H:%M:%S')}") # Timestamps in tuxedo!

Taking a modern, object-oriented approach with pathlib

Introduced in Python 3.4, pathlib provides a more object-oriented approach to file operations. It's more powerful and certainly more Pythonic. Here's a simple example:

from pathlib import Path mystery_file = Path("mystery_document.txt") if mystery_file.exists(): create_time = mystery_file.stat().st_ctime modify_time = mystery_file.stat().st_mtime print(f"Created on: {datetime.fromtimestamp(create_time)} # This file's first cry.") print(f"Last modified on: {datetime.fromtimestamp(modify_time)} # The last time this file went under the knife.")

The idiosyncrasies of timestamps

Even in the world of file timestamps, not all things are created equal. Here are some edge cases to look out for:

  • Linux's inode change time: os.path.getctime() on Linux is somewhat misleading as it returns the last inode change time, not the file creation time.
  • Filesystems Implications: Filesystems like ext4 on Linux do store file creation time, but Python's os module hasn't gotten the memo yet.
  • Timezone Considerations: Python timestamps are in UTC. If you need to display in local time, make sure to convert:
import time local_time = time.localtime(create_time_epoch) print(f"Local Creation Time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)} # Time has a place, and it's called TZ.")

Troubleshooting and further research

File System Support: Some file systems don't support creation time, without which you're out of luck. Permissions: You can't access file metadata without corresponding permissions. Symbolic Links: Make sure you fetch the metadata of the actual file, not the symbolic link.

For coders going the extra mile

Bulk Operations: If you deal with numerous files, use batch operations to improve efficiency. Caching: Frequently accessed files? Consider caching their timestamps to avoid redundant disk I/O. Alternative Libraries: Try scandir for efficient directory traversal or Watchdog to monitor file system events in real-time.