How to Get File Modified Time in Python Easily
os.path.getmtime(path) to get the file's last modified time as a timestamp, then convert it to a readable format with datetime.fromtimestamp(). This gives you the exact date and time when the file was last changed.Syntax
The main function to get a file's modified time is os.path.getmtime(path). It returns the time as a number representing seconds since January 1, 1970 (called a timestamp). To make this readable, use datetime.fromtimestamp(timestamp) to convert it to a normal date and time.
path: The file path as a string.os.path.getmtime(path): Returns the last modified time as a timestamp (float).datetime.fromtimestamp(timestamp): Converts timestamp to a human-readable date and time.
import os from datetime import datetime file_path = 'example.txt' modified_time = os.path.getmtime(file_path) readable_time = datetime.fromtimestamp(modified_time) print(readable_time)
Example
This example shows how to get the last modified time of a file named example.txt and print it in a readable format.
import os from datetime import datetime file_path = 'example.txt' # Get the last modified time as a timestamp modified_timestamp = os.path.getmtime(file_path) # Convert timestamp to readable date and time modified_time = datetime.fromtimestamp(modified_timestamp) print(f"File '{file_path}' was last modified on: {modified_time}")
Common Pitfalls
1. File Not Found Error: If the file path is wrong or the file does not exist, os.path.getmtime() will raise a FileNotFoundError. Always check the file exists before calling.
2. Timezone Confusion: The timestamp is in your system's local time zone when converted with datetime.fromtimestamp(). Use datetime.utcfromtimestamp() if you want UTC time.
3. Using Strings Directly: Don't try to print the timestamp number directly without converting; it will be hard to understand.
import os from datetime import datetime file_path = 'missing.txt' # Wrong way: no check for file existence try: modified_timestamp = os.path.getmtime(file_path) except FileNotFoundError: print(f"File '{file_path}' not found.") # Right way: check file exists first if os.path.exists(file_path): modified_timestamp = os.path.getmtime(file_path) modified_time = datetime.fromtimestamp(modified_timestamp) print(f"File '{file_path}' last modified on: {modified_time}") else: print(f"File '{file_path}' does not exist.")
Quick Reference
| Function | Purpose | Notes |
|---|---|---|
| os.path.getmtime(path) | Get file modified time as timestamp | Raises FileNotFoundError if file missing |
| datetime.fromtimestamp(timestamp) | Convert timestamp to local datetime | Readable date and time |
| datetime.utcfromtimestamp(timestamp) | Convert timestamp to UTC datetime | Use for timezone-independent time |
| os.path.exists(path) | Check if file exists | Avoid errors before getting time |