Is there a way to get the date a file or folder was last modified into python?

Dani AI

Generated

The quick solution posted by (and 's import fix) will get you the file timestamp. For readers coming later, here are clearer, more robust options and a few platform caveats to avoid subtle bugs.

For Python 3, prefer pathlib and datetime to produce readable, timezone-aware datetimes instead of manual time formatting. The snippet below shows a concise pattern to turn a file's modification timestamp into an ISO timestamp you can compare reliably.

from pathlib import Path
from datetime import datetime, timezone

p = Path("path/to/file")
ts = p.stat().st_mtime
dt = datetime.fromtimestamp(ts, tz=timezone.utc).astimezone()  # convert to local tz
print(dt.isoformat())

To get the most recently modified entry inside a folder, iterate with Path.iterdir() and pick the max by stat().st_mtime. Wrap stat() calls in try/except to handle missing files or permission errors.

A few important notes:

  • st_mtime (and getmtime) is a POSIX timestamp (float seconds since epoch). Use timezone-aware datetime objects when comparing times across systems.
  • ctime means different things: on Windows it is creation time; on Unix it is metadata-change time — do not rely on it for creation timestamps. See the Python docs for details on os.path and pathlib.Path.stat() for platform behavior.
  • Filesystem and network mounts can change timestamp resolution or produce skewed times (FAT has coarse resolution; network shares may report UTC). If you need to set timestamps, use os.utime or Path.touch with care.

These patterns handle common needs (display, comparison, latest-file) while avoiding pitfalls that show up across platforms and filesystems.

Recommended Answers

All 3 Replies

There certainly is a way!

import os

path = "path here"
seconds = os.path.getmtime(path)
print time.strftime('%Y-%m-%d %H:%M', time.localtime(seconds)
#it will output the time last modified!

It also needs

import time

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.