PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » File Handling » Python Get File Creation and Modification DateTime

Python Get File Creation and Modification DateTime

Updated on: December 4, 2026 | 3 Comments

In this tutorial, you’ll learn how to get the creation and modification datetime of a file in Python. This is useful for cleaning up old log files, finding the newest file in a folder, or showing a “last updated” date.

Python stores these times as timestamps (seconds since 1 January 1970). We’ll get them with the os and pathlib modules, then convert them into readable dates.

os.path module:

  • os.path.getmtime(path): The time the file’s content was last modified. Works on every operating system.
  • os.path.getatime(path): The time the file was last accessed (read).
  • os.path.getctime(path): On Windows, the creation time (deprecated for this purpose since Python 3.12). On Linux and macOS, the time the file’s metadata last changed, which is not the creation time.
  • os.stat(path).st_birthtime: The real creation time, where the system provides it (macOS, BSD, and Windows on Python 3.12+).

pathlib module:

  • Path(path).stat().st_mtime: The modern, object-oriented way to get the modification time.
  • Path(path).stat().st_birthtime / st_ctime: The same creation-time rules as above.

Table of contents

  • How to Get File Modification and Creation Time in Python
    • Example to Get File Modification and Creation Time
  • Get File Creation Datetime on Mac and Unix Systems
  • pathlib Module to Get the Creation and Modification Datetime of a File
    • Example
  • Get the Modification Time in UTC
  • Find Files Modified in the Last N Days
  • Sort Files by Modification Time
  • Summary

How to Get File Modification and Creation Time in Python

The steps below show how to use the os.path module and the datetime module to get the modification and creation time of a file in Python.

  1. Import the os and datetime modules

    The os.path module has functions to read a file’s metadata. The datetime module converts the timestamps it returns into readable dates.

  2. Get the modification time with getmtime()

    os.path.getmtime(path) returns the time of the last modification as a float timestamp. The path can be absolute or relative to the current folder.

  3. Convert the timestamp to a datetime

    Pass the timestamp to datetime.fromtimestamp() to get a datetime object in your local time. Then format it with strftime(), for example as DD-MM-YYYY HH:MM:SS.

  4. Get the creation time

    On Windows, os.path.getctime(path) returns the creation time. On macOS (and on Windows with Python 3.12+), use os.stat(path).st_birthtime. On Linux, getctime() returns the last metadata change instead, and the creation time usually isn’t available to Python.

Example to Get File Modification and Creation Time

To make this example runnable anywhere, we first create a small file. In your own code, use the path to an existing file, for example r"E:\demos\sample.txt" on Windows or "/Users/me/sample.txt" on macOS.

import os
from datetime import datetime

path = 'sample.txt'

# create a sample file
with open(path, 'w') as f:
    f.write('Hello, PYnative!')

# modification time as a timestamp
m_time = os.path.getmtime(path)
print('Timestamp:', m_time)

# convert the timestamp into a datetime object
dt_m = datetime.fromtimestamp(m_time)
print('Modified on:', dt_m)
print('Formatted:', dt_m.strftime('%d-%m-%Y %H:%M:%S'))

# on Windows this is the creation time; on Linux/macOS it's the metadata change time
c_time = os.path.getctime(path)
print('ctime:', datetime.fromtimestamp(c_time))Code language: Python (python)

Output:

Timestamp: 1796026075.6479409
Modified on: 2026-11-30 13:37:55.647941
Formatted: 30-11-2026 13:37:55
ctime: 2026-11-30 13:37:55.647941

Your output will show the date and time when you run the program, because we just created the file. To display dates in other formats, see Python Datetime formatting.

Get File Creation Datetime on Mac and Unix Systems

  • On macOS and BSD systems, the st_birthtime attribute of the result of os.stat() holds the file’s creation time.
  • On Windows, st_birthtime is available from Python 3.12. Before that, use st_ctime (or getctime()).
  • On Linux, os.stat() doesn’t provide st_birthtime, so accessing it raises an AttributeError.

This function works on every system. It returns the creation time where it’s available and falls back to the modification time otherwise:

import os
from datetime import datetime

def creation_time(path):
    stat = os.stat(path)
    try:
        # macOS, BSD, and Windows (Python 3.12+)
        timestamp = stat.st_birthtime
    except AttributeError:
        # Linux: creation time not available, use the last modification time
        timestamp = stat.st_mtime
    return datetime.fromtimestamp(timestamp)

with open('sample.txt', 'w') as f:
    f.write('demo')

print('Created (or modified) on:', creation_time('sample.txt'))Code language: Python (python)

Output:

Created (or modified) on: 2026-11-30 13:37:55.663400

Why is the creation time so hard to get? Not every file system records it, and operating systems expose it in different ways. That’s why the modification time (st_mtime) is the most reliable, portable value. If your program decides things based on file age, use the modification time.

pathlib Module to Get the Creation and Modification Datetime of a File

The pathlib module (Python 3.4+) represents file paths as objects. It works the same way on Windows, macOS, and Linux, and many developers find it cleaner than os.path.

  1. Create a Path object: Path('sample.txt') represents the file. On Windows it becomes a WindowsPath, and on other systems a PosixPath.
  2. Call the stat() method: It returns the file’s metadata, including its size and timestamps.
  3. Read the timestamp attributes: st_mtime is the last modification time and st_atime the last access time. st_ctime follows the same platform rules as getctime(). These are attributes, so write them without parentheses.
  4. Convert to a datetime: Pass the timestamp to datetime.fromtimestamp().

Example

from datetime import datetime
from pathlib import Path

file = Path('report.txt')
file.write_text('Monthly report')

info = file.stat()

m_time = datetime.fromtimestamp(info.st_mtime)
a_time = datetime.fromtimestamp(info.st_atime)

print('Size:', info.st_size, 'bytes')
print('Modified on:', m_time.strftime('%Y-%m-%d %H:%M:%S'))
print('Accessed on:', a_time.strftime('%Y-%m-%d %H:%M:%S'))Code language: Python (python)

Output:

Size: 14 bytes
Modified on: 2026-11-30 13:37:55
Accessed on: 2026-11-30 13:37:55

Note: Don’t rely on the access time (st_atime). To improve performance, many systems update it only occasionally or not at all, so it may not change when a file is read.

All of these functions raise a FileNotFoundError if the file doesn’t exist. Check the path with Path.exists() first, or wrap the call in a try-except block.

Get the Modification Time in UTC

datetime.fromtimestamp(ts) returns your local time. If you share the time with other systems or store it in a database, convert it to UTC by passing tz=timezone.utc. Here we use os.utime() to set a known modification time so the output is the same on every computer:

import os
from datetime import datetime, timezone

path = 'sample.txt'
with open(path, 'w') as f:
    f.write('demo')

# set access and modification time to 2022-01-15 10:30:00 UTC
fixed = datetime(2022, 1, 15, 10, 30, tzinfo=timezone.utc).timestamp()
os.utime(path, (fixed, fixed))

m_time = os.path.getmtime(path)
print('UTC:', datetime.fromtimestamp(m_time, tz=timezone.utc))
print('ISO:', datetime.fromtimestamp(m_time, tz=timezone.utc).isoformat())Code language: Python (python)

Output:

UTC: 2022-01-15 10:30:00+00:00
ISO: 2022-01-15T10:30:00+00:00

os.utime(path, (atime, mtime)) changes a file’s access and modification times. Calling os.utime(path) without times sets both to now, much like the Unix touch command (or Path.touch() in pathlib).

Find Files Modified in the Last N Days

A common real-world task is finding recently changed files, or old files to delete. Compare each file’s modification time with a cutoff date:

import os
import time
from datetime import datetime, timedelta
from pathlib import Path

folder = Path('logs')
folder.mkdir(exist_ok=True)

# create three log files with different ages
now = time.time()
for name, days_old in [('today.log', 0), ('last_week.log', 6), ('old.log', 40)]:
    file = folder / name
    file.write_text('log data')
    t = now - days_old * 86400
    os.utime(file, (t, t))

cutoff = datetime.now() - timedelta(days=7)

for file in sorted(folder.iterdir()):
    modified = datetime.fromtimestamp(file.stat().st_mtime)
    status = 'recent' if modified >= cutoff else 'older than 7 days'
    print(f'{file.name:15} {status}')Code language: Python (python)

Output:

last_week.log   recent
old.log         older than 7 days
today.log       recent

To delete old files, replace the print() with file.unlink() for the old ones. Test with print() first, because deleted files don’t go to the recycle bin.

Sort Files by Modification Time

Use sorted() with a key that returns each file’s st_mtime. Add reverse=True to put the newest file first:

import os
import time
from pathlib import Path

folder = Path('reports')
folder.mkdir(exist_ok=True)

now = time.time()
for i, name in enumerate(['jan.csv', 'feb.csv', 'mar.csv']):
    file = folder / name
    file.write_text('data')
    t = now - (3 - i) * 3600   # each file one hour newer than the last
    os.utime(file, (t, t))

files = sorted(folder.iterdir(), key=lambda f: f.stat().st_mtime, reverse=True)
print('Newest first:', [f.name for f in files])

latest = max(folder.iterdir(), key=lambda f: f.stat().st_mtime)
print('Latest file:', latest.name)Code language: Python (python)

Output:

Newest first: ['mar.csv', 'feb.csv', 'jan.csv']
Latest file: mar.csv

To learn more about working with files, see the Python file handling tutorials.

Summary

TaskUse
Last modification timeos.path.getmtime(p) or Path(p).stat().st_mtime
Last access timeos.path.getatime(p) or Path(p).stat().st_atime
Creation time (macOS, Windows 3.12+)os.stat(p).st_birthtime
Creation time (Windows, Python 3.11 and older)os.path.getctime(p)
Timestamp to local datetimedatetime.fromtimestamp(ts)
Timestamp to UTC datetimedatetime.fromtimestamp(ts, tz=timezone.utc)
Change modification timeos.utime(p, (atime, mtime))

Filed Under: Python, Python DateTime, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python DateTime Python File Handling

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Guy says

    March 21, 2024 at 10:59 pm

    it is so sad that everyone is still using old functions to set datetime? newer function allows to set any date (even below 1970), But I cannot find the systax of it in Python.

    Reply
  2. Weichao Wang says

    September 15, 2023 at 12:43 pm

    A very good article: an overview at the beginning, detailed description and examples in the main text, just in the style of K&R’s “C Programming Language”, I like it!

    Reply
  3. imtiaz says

    June 15, 2022 at 6:23 pm

    How can I get file creation datetime from SFTP location?

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python DateTime Python File Handling
TweetF  sharein  shareP  Pin

  Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com