W3docs

How do I get file creation and modification date/times?

There are a few ways to get the file creation and modification date/times, depending on the programming language and operating system you are using.

There are a few ways to get the file creation and modification date/times, depending on the programming language and operating system you are using. Here are a few examples:

In Python, you can use the os.path module or pathlib to get the file's creation and modification date/times:

Using the os.path and pathlib methods to get a file's creation and modification date in Python

import os
from pathlib import Path

file_path = '/path/to/file.txt'

# Get file modification time
mod_time = os.path.getmtime(file_path)

# Get file creation time (Windows only; on Unix it returns metadata change time)
create_time = os.path.getctime(file_path)

# Cross-platform alternative using pathlib
p = Path(file_path)
mod_time_pathlib = p.stat().st_mtime
create_time_pathlib = p.stat().st_ctime

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

In Java, you can use the java.nio.file.Files class to get the file's last modified and creation dates:

Using the java.nio.file.Files method to get a file's last modification date in Java

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Path path = Paths.get("/path/to/file.txt");
long lastModified = Files.getAttribute(path, "lastModifiedTime").toMillis();
long creationTime = Files.getAttribute(path, "creationTime").toMillis();

In bash, you can use the stat command to get the file's creation and modification date/times:

Using the stat command to get a file's last modification date in Bash

# Get file modification time
# macOS/BSD: stat -f "%m" /path/to/file.txt
# Linux: stat -c "%Y" /path/to/file.txt

# Get file creation time (macOS/BSD only; Linux typically doesn't expose it via stat)
# macOS/BSD: stat -f "%B" /path/to/file.txt

Please note that file creation time is not available on all operating systems, and the above examples may not work on all OS.