How to check file last access time using Python?

Monitoring file access times is a common requirement for auditing, data management and cleanup scripts. Python provides multiple ways to retrieve the last access time of a file using the os and pathlib modules.

Using os.path.getatime() Method

The os.path.getatime() method retrieves a file's most recent access time. It takes the file path as input and returns the time since epoch as a floating-point number.

Syntax

os.path.getatime(path)

Example 1: Basic Usage

Here's how to check a file's last access time using os.path.getatime() ?

import os
import datetime

# Create a sample file for demonstration
with open('sample.txt', 'w') as f:
    f.write('Hello World!')

# Get last access time
last_access_time = os.path.getatime('sample.txt')
readable_time = datetime.datetime.fromtimestamp(last_access_time)
print(f'File last access time: {readable_time}')
File last access time: 2024-01-15 10:30:45.123456

Example 2: Using time Module

You can format the timestamp using the time module for different display formats ?

import os
import time

# Create a sample file
with open('demo.txt', 'w') as f:
    f.write('Demo content')

# Get access time and format it
access_time_epoch = os.path.getatime('demo.txt')
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(access_time_epoch))
print(f"Last access time: {formatted_time}")

# UTC format
utc_time = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(access_time_epoch))
print(f"UTC time: {utc_time}")
Last access time: 2024-01-15 10:30:45
UTC time: 2024-01-15 05:30:45 UTC

Using os.stat() Method

The os.stat() method returns comprehensive file statistics, including access time, modification time, and file size.

Syntax

os.stat(filepath)

Example

Using os.stat() to get file access time ?

import os
import time

# Create a sample file
with open('test_file.txt', 'w') as f:
    f.write('Test content')

# Get file statistics
file_stats = os.stat('test_file.txt')

# Extract access time
last_access = time.ctime(file_stats.st_atime)
print(f"Last access time: {last_access}")

# Also show modification and creation times
modification_time = time.ctime(file_stats.st_mtime)
print(f"Last modification: {modification_time}")
Last access time: Mon Jan 15 10:30:45 2024
Last modification: Mon Jan 15 10:30:45 2024

Using pathlib Module

The modern pathlib module provides an object-oriented approach to file operations ?

from pathlib import Path
import datetime

# Create a sample file
file_path = Path('pathlib_demo.txt')
file_path.write_text('Pathlib demo content')

# Get access time using pathlib
access_time = file_path.stat().st_atime
readable_time = datetime.datetime.fromtimestamp(access_time)
print(f"Access time (pathlib): {readable_time}")
Access time (pathlib): 2024-01-15 10:30:45.123456

Error Handling

Always handle potential errors when accessing file information ?

import os
import datetime

def get_file_access_time(filepath):
    try:
        access_time = os.path.getatime(filepath)
        return datetime.datetime.fromtimestamp(access_time)
    except OSError as e:
        return f"Error: {e}"
    except FileNotFoundError:
        return "File not found"

# Test with existing and non-existing files
print(get_file_access_time('sample.txt'))  # Existing file
print(get_file_access_time('nonexistent.txt'))  # Non-existing file
2024-01-15 10:30:45.123456
File not found

Comparison of Methods

Method Return Type Best For
os.path.getatime() Float (seconds since epoch) Simple access time queries
os.stat() stat_result object Multiple file attributes needed
pathlib.Path.stat() stat_result object Modern, object-oriented approach

Conclusion

Use os.path.getatime() for simple access time queries, os.stat() when you need multiple file attributes, and pathlib for modern Python applications. Always include error handling for robust file operations.

Updated on: 2026-03-24T18:36:53+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements