Freezegun: Time Travel for Your Python Tests

This repository profile is provided by osrepos.com, an open source repository discovery platform.

Freezegun: Time Travel for Your Python Tests

Summary

Freezegun is a powerful Python library designed to simplify testing by allowing your tests to travel through time. It achieves this by mocking the `datetime` module, enabling developers to freeze time at a specific point or even simulate its progression. This functionality is crucial for ensuring consistent and reliable test results when dealing with time-sensitive logic.

Repository Information

Analyzed by OSRepos on August 4, 2026

Topics

Click on any tag to explore related repositories

Use at your own risk

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of code from these repositories is the user's own responsibility. Always review the repository, source code, dependencies, licenses, and security implications before running or installing anything. OSRepos is not responsible for issues, damages, or losses resulting from third-party repositories.

Introduction

Freezegun is an indispensable Python library that empowers developers to manipulate time within their test suites. By effectively mocking the datetime module, time.time(), and related functions, Freezegun allows you to freeze the current time to a specific date and time, or even simulate the passage of time. This capability is vital for testing applications with time-dependent features, ensuring that your tests are deterministic and free from real-world time variations.

Installation

Installing Freezegun is straightforward using pip:

$ pip install freezegun

For Debian systems, you can also use apt-get:

$ sudo apt-get install python-freezegun

Examples

Freezegun offers flexible ways to control time, whether through decorators, context managers, or direct API calls.

Decorator Usage

Apply freeze_time as a decorator to functions or classes to freeze time for their duration.

from freezegun import freeze_time
import datetime
import unittest

# Freeze time for a pytest style test:
@freeze_time("2012-01-14")
def test_frozen_time_decorator():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)

# Or a unittest TestCase:
@freeze_time("1955-11-12")
class MyTests(unittest.TestCase):
    def test_the_class(self):
        assert datetime.datetime.now() == datetime.datetime(1955, 11, 12)

Context Manager Usage

Use freeze_time as a context manager for precise control over time within a specific block of code.

from freezegun import freeze_time
import datetime

def test_time_context_manager():
    assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
    with freeze_time("2012-01-14"):
        assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
    assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)

Manual Ticks and Moving Time

Beyond freezing, Freezegun allows you to manually advance time or jump to a specific date.

from freezegun import freeze_time
import datetime

def test_manual_tick_and_move():
    initial_datetime = datetime.datetime(year=1, month=7, day=12,
                                        hour=15, minute=6, second=3)
    with freeze_time(initial_datetime) as frozen_datetime:
        assert frozen_datetime() == initial_datetime

        # Manually advance time by 1 second
        frozen_datetime.tick()
        initial_datetime += datetime.timedelta(seconds=1)
        assert frozen_datetime() == initial_datetime

        # Move to a completely different date
        other_datetime = datetime.datetime(year=2, month=8, day=13,
                                            hour=14, minute=5, second=0)
        frozen_datetime.move_to(other_datetime)
        assert frozen_datetime() == other_datetime

Ticking Time

The tick=True argument allows time to progress naturally from the frozen point.

from freezegun import freeze_time
import datetime
import time

@freeze_time("Jan 14th, 2020", tick=True)
def test_ticking_time():
    # Time will progress naturally after the initial freeze point
    initial_time = datetime.datetime.now()
    time.sleep(0.01) # Simulate some time passing
    assert datetime.datetime.now() > initial_time

Auto-Ticking Time

The auto_tick_seconds argument automatically increments time by a specified amount on each call.

from freezegun import freeze_time
import datetime

@freeze_time("Jan 14th, 2020", auto_tick_seconds=15)
def test_auto_ticking_time():
    first_time = datetime.datetime.now()
    # Subsequent call to datetime.datetime.now() will be 15 seconds later
    auto_incremented_time = datetime.datetime.now()
    assert first_time + datetime.timedelta(seconds=15) == auto_incremented_time

Real Asyncio

For asyncio applications, real_asyncio=True allows asyncio event loops to see real monotonic time while datetime remains frozen.

from freezegun import freeze_time
import datetime
import asyncio

@freeze_time("2012-01-14", real_asyncio=True)
async def test_asyncio_with_frozen_time():
    start_time = datetime.datetime.now()
    await asyncio.sleep(0.1) # This sleep will use real time
    end_time = datetime.datetime.now()
    assert start_time == end_time # datetime is still frozen

Why Use Freezegun?

Testing applications that interact with dates and times can be notoriously difficult. Real-world time is constantly changing, making it hard to reproduce specific scenarios or ensure consistent test results. Freezegun solves this by providing a simple, elegant way to control time within your tests. This leads to more reliable, deterministic, and faster test suites, allowing you to focus on your application's logic rather than battling time-related inconsistencies. It's an essential tool for any Python developer working with datetime objects in their code.

Links

Explore the Freezegun project further:

Related repositories

Similar repositories that may be relevant next.

oh-my-hermes: Enhance Hermes Agent with Advanced AI Workflow and Memory

oh-my-hermes: Enhance Hermes Agent with Advanced AI Workflow and Memory

September 17, 2026

oh-my-hermes is an all-in-one plugin designed to significantly enhance the Hermes Agent. It provides advanced coding intelligence, a robust long-term memory system, and optimized workflow packages, transforming standard Hermes requests into structured, actionable tasks with clear operational layers.

AI AgentHermes AgentAI Tools
ASC: A Super Fast Android Decompiler for Mobile Reverse Engineering

ASC: A Super Fast Android Decompiler for Mobile Reverse Engineering

September 17, 2026

ASC is an innovative and exceptionally fast Android decompiler front-end, specifically designed for mobile researchers and agents. It redefines traditional decompilation by directly querying compiled artifacts, offering on-demand code extraction and analysis without heavy preprocessing. This approach results in significantly reduced memory usage and lightning-fast performance, even on large APKs.

AndroidDecompilerReverse Engineering
Open Index: A Deterministic Memory Layer for Your AI Agents

Open Index: A Deterministic Memory Layer for Your AI Agents

September 16, 2026

Open Index is a powerful tool for building domain-specific, accurate, and structured data that AI agents can effectively operate on. It enables the creation of a "brain," a searchable and continuously improving context graph tailored to any domain. This system ensures agents have access to reliable, up-to-date information, enhancing their capabilities and decision-making processes.

AI AgentsKnowledge GraphAgent Memory
tooltrim: Drastically Reduce LLM Agent Tool Output Tokens, Improve Accuracy

tooltrim: Drastically Reduce LLM Agent Tool Output Tokens, Improve Accuracy

September 16, 2026

tooltrim provides drop-in compression for LLM agent tool outputs, drastically cutting tokens while often improving answer accuracy. This provider-agnostic solution offers content-aware compression, faithfulness benchmarks, and seamless integration with popular frameworks or as an OpenAI-compatible proxy.

PythonLLM AgentsContext Compression

Source repository

Open the original repository on GitHub.

14 counted GitHub visits

View on GitHub
OS
OSRepos

Analysis and discovery of open source repositories. Find interesting projects and follow their updates.

Monitor your website with YourWebsiteScore

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of third-party repository code is at your own risk. Always review source code, dependencies, licenses, and security implications before running anything.

© 2025 OSRepos. Built with Nuxt 3 and lots of ❤️