0
0
PythonHow-ToBeginner · 3 min read

How to Get File Modified Time in Python Easily

Use 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.
python
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)
Output
2024-06-01 14:23:45.123456
💻

Example

This example shows how to get the last modified time of a file named example.txt and print it in a readable format.

python
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}")
Output
File 'example.txt' was last modified on: 2024-06-01 14:23:45.123456
⚠️

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.

python
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.")
Output
File 'missing.txt' not found. File 'missing.txt' does not exist.
📊

Quick Reference

FunctionPurposeNotes
os.path.getmtime(path)Get file modified time as timestampRaises FileNotFoundError if file missing
datetime.fromtimestamp(timestamp)Convert timestamp to local datetimeReadable date and time
datetime.utcfromtimestamp(timestamp)Convert timestamp to UTC datetimeUse for timezone-independent time
os.path.exists(path)Check if file existsAvoid errors before getting time

Key Takeaways

Use os.path.getmtime() to get the file's last modified time as a timestamp.
Convert the timestamp to readable date and time with datetime.fromtimestamp().
Always check if the file exists before getting its modified time to avoid errors.
Remember the time is in local timezone unless you use utcfromtimestamp().
Printing the raw timestamp is not user-friendly; convert it first.