How to Get File Creation and Modification Date or Time in Python
Retrieving file creation and modification times is a common task in Python, useful for log management, file synchronization, backup systems, and data processing pipelines. Python provides several ways to access these timestamps using built-in modules. In this guide, we'll cover the most practical methods, show how to format the timestamps, and explain the important cross-platform differences.
Quick Answer
import os
from datetime import datetime
path = "myfile.txt"
# Modification time
mod_time = datetime.fromtimestamp(os.path.getmtime(path))
print(f"Modified: {mod_time}")
# Creation time (see platform note below)
create_time = datetime.fromtimestamp(os.path.getctime(path))
print(f"Created: {create_time}")
Output:
Modified: 2025-07-07 16:25:52.490759
Created: 2025-06-27 14:16:30.123721
getctime() Behavior- Windows:
os.path.getctime()returns the file creation time. - Linux/macOS:
os.path.getctime()returns the time of the last metadata change (for example, permissions, ownership), which is not the creation time.
To get the true creation time on macOS, use os.stat(path).st_birthtime. On Linux, true creation time (birth time) is only available on certain filesystems (ext4 with kernel 4.11+) via os.stat(path).st_birthtime (Python 3.12+).
Method 1: Using os.path with time Module
The os.path module provides getmtime() and getctime(), which return timestamps as seconds since epoch (January 1, 1970). The time module's ctime() function converts these to a human-readable string.
import os
import time
path = "myfile.txt"
# Get timestamps (seconds since epoch)
mod_timestamp = os.path.getmtime(path)
create_timestamp = os.path.getctime(path)
# Convert to readable strings
mod_readable = time.ctime(mod_timestamp)
create_readable = time.ctime(create_timestamp)
print(f"Modified: {mod_readable}")
print(f"Created: {create_readable}")
Output:
Modified: Mon Jul 7 16:25:52 2025
Created: Fri Jun 27 14:16:30 2025
Custom Format with strftime()
To format the timestamp in a specific way (for example, ISO 8601):
import os
import time
path = "myfile.txt"
mod_timestamp = os.path.getmtime(path)
time_struct = time.localtime(mod_timestamp)
# ISO 8601 format
formatted = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)
print(f"Modified: {formatted}")
# Custom format
custom = time.strftime("%B %d, %Y at %I:%M %p", time_struct)
print(f"Modified: {custom}")
Output:
Modified: 2025-07-07 16:25:52
Modified: July 07, 2025 at 04:25 PM
Method 2: Using os.path with datetime Module
The datetime module provides a more versatile way to work with timestamps:
import os
from datetime import datetime
path = "myfile.txt"
# Modification time as datetime object
mod_time = datetime.fromtimestamp(os.path.getmtime(path))
print(f"Modified: {mod_time}")
# Creation time as datetime object
create_time = datetime.fromtimestamp(os.path.getctime(path))
print(f"Created: {create_time}")
# Custom formatting
print(f"Modified (ISO): {mod_time.isoformat()}")
print(f"Modified (custom): {mod_time.strftime('%d/%m/%Y %H:%M')}")
Output:
Modified: 2025-07-07 16:25:52.490759
Created: 2025-06-27 14:16:30.123721
Modified (ISO): 2025-07-07T16:25:52.490759
Modified (custom): 07/07/2025 16:25
Working with Timezones
For timezone-aware timestamps:
import os
from datetime import datetime, timezone
path = "myfile.txt"
# UTC timestamp
mod_time_utc = datetime.fromtimestamp(
os.path.getmtime(path), tz=timezone.utc
)
print(f"Modified (UTC): {mod_time_utc.isoformat()}")
# Local timestamp
mod_time_local = datetime.fromtimestamp(os.path.getmtime(path))
print(f"Modified (local): {mod_time_local.isoformat()}")
Output:
Modified (UTC): 2025-07-07T10:25:52.490759+00:00
Modified (local): 2025-07-07T16:25:52.490759
Method 3: Using pathlib.Path (Modern Python)
pathlib provides a clean, object-oriented approach:
from pathlib import Path
from datetime import datetime
path = Path("myfile.txt")
# Using .stat() to get file metadata
stat = path.stat()
mod_time = datetime.fromtimestamp(stat.st_mtime)
create_time = datetime.fromtimestamp(stat.st_ctime)
access_time = datetime.fromtimestamp(stat.st_atime)
print(f"Modified: {mod_time}")
print(f"Created/Meta: {create_time}")
print(f"Last Access: {access_time}")
print(f"Size: {stat.st_size:,} bytes")
Output:
Modified: 2025-07-07 16:25:52.490759
Created/Meta: 2025-06-27 14:16:30.123721
Last Access: 2025-07-23 09:15:00.000000
Size: 1,247 bytes
Available Timestamp Attributes from stat()
| Attribute | Description |
|---|---|
st_mtime | Last modification time (content changed) |
st_ctime | Creation time (Windows) / metadata change time (Linux/macOS) |
st_atime | Last access time (file was read) |
st_birthtime | True creation time (macOS; Python 3.12+ on Linux with ext4) |
st_size | File size in bytes |
Method 4: Using os.stat() Directly
os.stat() returns a stat result object with all file metadata:
import os
from datetime import datetime
path = "myfile.txt"
stat = os.stat(path)
print(f"Modification time: {datetime.fromtimestamp(stat.st_mtime)}")
print(f"Creation/Meta time: {datetime.fromtimestamp(stat.st_ctime)}")
print(f"Access time: {datetime.fromtimestamp(stat.st_atime)}")
Getting True Creation Time Cross-Platform
Since st_ctime means different things on different platforms, here's a helper function that gets the true creation time where possible:
import os
import platform
from datetime import datetime
from pathlib import Path
def get_creation_time(filepath):
"""Get the file creation time, cross-platform."""
stat = os.stat(filepath)
if platform.system() == 'Windows':
# Windows: st_ctime is the creation time
return datetime.fromtimestamp(stat.st_ctime)
elif platform.system() == 'Darwin':
# macOS: st_birthtime is the true creation time
return datetime.fromtimestamp(stat.st_birthtime)
else:
# Linux: st_birthtime available on Python 3.12+ with ext4
# Fall back to st_mtime if not available
try:
return datetime.fromtimestamp(stat.st_birthtime)
except AttributeError:
# st_birthtime not available: use the earlier of ctime and mtime
return datetime.fromtimestamp(min(stat.st_ctime, stat.st_mtime))
path = "myfile.txt"
print(f"Created: {get_creation_time(path)}")
print(f"Modified: {datetime.fromtimestamp(os.path.getmtime(path))}")
Practical Examples
Checking If a File Was Modified Recently
from pathlib import Path
from datetime import datetime, timedelta
path = Path("myfile.txt")
mod_time = datetime.fromtimestamp(path.stat().st_mtime)
age = datetime.now() - mod_time
if age < timedelta(hours=24):
print(f"File was modified {age.total_seconds() / 3600:.1f} hours ago (recent)")
elif age < timedelta(days=7):
print(f"File was modified {age.days} days ago")
else:
print(f"File was modified on {mod_time.strftime('%Y-%m-%d')} ({age.days} days ago)")
Output:
File was modified 16 days ago
Finding the Most Recently Modified File in a Directory
from pathlib import Path
from datetime import datetime
directory = Path(".")
files = [(f, f.stat().st_mtime) for f in directory.iterdir() if f.is_file()]
if files:
# Sort by modification time (newest first)
files.sort(key=lambda x: x[1], reverse=True)
print("Most recently modified files:")
for f, mtime in files[:5]:
mod_time = datetime.fromtimestamp(mtime)
print(f" {mod_time.strftime('%Y-%m-%d %H:%M')} {f.name}")
Output:
Most recently modified files:
2025-07-23 09:15 report.py
2025-07-22 14:30 data.csv
2025-07-20 11:00 config.json
2025-07-18 08:45 utils.py
2025-07-15 16:20 README.md
Getting File Info as a Dictionary
from pathlib import Path
from datetime import datetime
def get_file_info(filepath):
"""Return a dictionary of file metadata."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
stat = path.stat()
return {
"name": path.name,
"directory": str(path.parent.resolve()),
"size_bytes": stat.st_size,
"size_readable": f"{stat.st_size / 1024:.1f} KB",
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
"created": datetime.fromtimestamp(stat.st_ctime).isoformat(),
"accessed": datetime.fromtimestamp(stat.st_atime).isoformat(),
"extension": path.suffix,
}
info = get_file_info("myfile.txt")
for key, value in info.items():
print(f" {key:15s}: {value}")
Output:
name : myfile.txt
directory : /home/user/project
size_bytes : 1247
size_readable : 1.2 KB
modified : 2025-07-07T16:25:52.490759
created : 2025-06-27T14:16:30.123721
accessed : 2025-07-23T09:15:00
extension : .txt
Common Format Specifiers
| Specifier | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2025 |
%m | Month (zero-padded) | 07 |
%d | Day (zero-padded) | 23 |
%H | Hour (24-hour) | 16 |
%I | Hour (12-hour) | 04 |
%M | Minute | 25 |
%S | Second | 52 |
%p | AM/PM | PM |
%B | Full month name | July |
%A | Full day name | Wednesday |
Method Comparison
| Method | Returns | Best For |
|---|---|---|
os.path.getmtime() | Float (seconds) | Quick modification time check |
os.path.getctime() | Float (seconds) | Creation time (Windows only) |
os.stat() | Stat result object | All file metadata at once |
pathlib.Path.stat() | Stat result object | Modern, object-oriented code |
datetime.fromtimestamp() | datetime object | Formatting and date arithmetic |
time.ctime() | String | Quick human-readable output |
Conclusion
To get file creation and modification times in Python, use os.path.getmtime() for modification time and convert it with datetime.fromtimestamp() for a readable format.
For modern Python code, pathlib.Path.stat() provides a clean, object-oriented approach to accessing all file metadata.
Remember that st_ctime means creation time on Windows but metadata change time on Linux/macOS; use st_birthtime on macOS for the true creation time. Format timestamps with strftime() to match your application's requirements.