Testland
Browse all skills & agents

freezegun-python

Wraps freezegun (github.com/spulec/freezegun), the Python time-mocking library: @freeze_time decorator / context manager, freeze_time(...).start() + stop(), tick / move_to / tz_offset, and integration with datetime.now / time.time / time.localtime. Use when testing Python code that calls datetime / time.

Install with skills.sh (any agent)

npx skills add testland/qa --skill freezegun-python
View source

freezegun-python

Overview

freezegun patches datetime.datetime, datetime.date, time.time, time.gmtime, time.localtime, time.strftime, and asyncio time across the test scope. Per github.com/spulec/freezegun (opens in new window).

When to use

  • pytest / unittest tests for Python code using datetime / time.
  • Date-based fixtures (e.g., "today is 2026-05-20").
  • DST + timezone tests per dst-transition-reference.

Authoring

Install

pip install freezegun

Decorator (most common)

from freezegun import freeze_time
from datetime import datetime

@freeze_time("2026-05-20T14:30:00")
def test_today_is_may_20():
    assert datetime.now().strftime("%Y-%m-%d") == "2026-05-20"

Context manager

with freeze_time("2026-05-20T14:30:00"):
    assert datetime.now().strftime("%Y-%m-%d") == "2026-05-20"

Manual start/stop

freezer = freeze_time("2026-05-20T14:30:00")
freezer.start()
try:
    # ...
finally:
    freezer.stop()

Tick mode

@freeze_time("2026-05-20T14:30:00", tick=True)
def test_clock_advances():
    t1 = datetime.now()
    # ... a few ops later
    t2 = datetime.now()
    assert t2 > t1

tick=True lets real time pass from the frozen start point. Useful for tests that need duration measurement.

Move to a different time mid-test

@freeze_time("2026-05-20T14:30:00")
def test_advance_one_day(freezer):
    assert datetime.now().day == 20
    freezer.move_to("2026-05-21T14:30:00")
    assert datetime.now().day == 21

Or via freezer.tick(delta=timedelta(hours=24)).

Timezone offset

@freeze_time("2026-05-20T14:30:00", tz_offset=-5)
def test_eastern_time():
    # datetime.now() returns wall-clock; datetime.utcnow() returns UTC
    assert datetime.utcnow().hour == 19  # 14:30 + 5
    assert datetime.now().hour == 14

DST, async, and CI

DST + zone tests, async support, and CI integration are in references/advanced-scenarios.md.

Running

pytest tests/

Anti-patterns

Anti-patternWhy it failsFix
freeze_time("2026-05-20") (date only)freezegun interprets as midnight local; subtleUse ISO datetime
time.sleep(...) inside frozen-time blockSleep is real-time; frozen clock doesn't advanceUse freezer.tick()
Mock datetime.utcnow separatelyConflicts with freezegunLet freezegun do both
Forget freezer cleanup in fixturesCross-test contaminationUse decorator or with
Test DST without tz_offset or zoneinfoResult is UTC; misses local behaviourCombine with zoneinfo
@freeze_time on a class without decorate_class=TrueMethods not patchedUse class decorator explicitly
Test third-party C extensions calling system timefreezegun only patches Python-level APIsUse libfaketime

Limitations

  • C extensions bypass freezegun. A library calling clock_gettime() from C sees the real clock. Use libfaketime-c for those.
  • No leap-second simulation. See leap-second-reference.
  • tz_offset doesn't know about DST. For accurate local-zone behaviour, use datetime.now(tz=zoneinfo.ZoneInfo("...")).
  • Importing datetime before freezing. If a module imports datetime.now directly at module-load, the unfrozen value may be cached.

References

freezegun advanced scenarios

View source (opens in new window)

freezegun advanced scenarios

DST/zone tests, async support, and CI wiring extracted from the core skill. Core decorator/context-manager/tick usage stays in SKILL.md.

DST + zone tests

tz_offset is a fixed offset and does not know about DST. For local-zone behaviour at a transition, freeze UTC and read through zoneinfo.

import pytest
from zoneinfo import ZoneInfo
from freezegun import freeze_time
from datetime import datetime

@freeze_time("2026-03-08T07:30:00")  # 02:30 EST OR 03:30 EDT - depends on resolution
def test_spring_forward_handling():
    ny = datetime.now(ZoneInfo("America/New_York"))
    # Asserts against expected library behaviour per dst-transition-reference

Async support

from freezegun import freeze_time
from datetime import datetime
import asyncio

@freeze_time("2026-05-20T14:30:00")
async def test_async_now():
    await asyncio.sleep(0)
    assert datetime.now().strftime("%Y") == "2026"

Per freezegun docs: "freezegun is compatible with asyncio."

CI integration

jobs:
  python-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v5
      - run: pip install -e ".[test]" freezegun
      - run: pytest tests/

Related skills

dotnet-faketime

Wraps .NET's TimeProvider abstraction (System.TimeProvider, introduced .NET 8) and FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing: SetUtcNow, Advance, AutoAdvanceAmount, CreateTimer, Delay, and the pre-.NET-8 ISystemClock migration path. Use when testing C# or F# code that reads the current time, uses timers, or awaits Task.Delay.

dst-transition-reference

Pure-reference catalog of Daylight Saving Time (DST) transition patterns and their canonical bug classes. Covers the spring-forward (skipped hour: 02:00 → 03:00 local) and fall-back (repeated hour: 02:00 → 01:00 local) transitions, the historical irregularity of DST (different jurisdictions, transitions on different dates, some regions abolish DST or never adopted it), the IANA timezone database (tz / Olson DB) as the canonical source, and the testable behaviors DST creates (duplicate / missing local timestamps, cron jobs that fire 0 or 2 times, billing periods that miss / double-count, recurring meetings on transition days). Per-jurisdiction DST-rule tables and refreshable per-region test-data fixtures live in references/. Use when designing or auditing time-handling code or test cases.

iso-8601-vs-rfc-3339-reference

Pure-reference catalog of the ISO 8601 vs RFC 3339 distinction. Covers the relationship (RFC 3339 is a strict subset of ISO 8601 designed for internet protocols), the syntactic differences (RFC 3339 disallows ISO 8601's '+02' offset short-form requires '+02:00'; RFC 3339 mandates a date-time separator T or space; ISO 8601 allows much more), the canonical date-time string format (YYYY-MM-DDTHH:MM:SS[.fff]±HH:MM or Z), per-language parser behaviour (Python isoformat, Java Instant.parse, JS Date.parse non-spec), and serialisation rules for APIs. Use when choosing a wire format, parsing third-party datetimes, or auditing time-string handling.

jest-fake-timers

Wraps Jest's built-in modern fake-timers (built on @sinonjs/fake-timers since Jest 27): jest.useFakeTimers(), jest.setSystemTime(), jest.advanceTimersByTime(), jest.runAllTimers(), and jest.useRealTimers() for selective restoration. Use when testing JS/TS code in Jest where setTimeout / setInterval / Date / Date.now need deterministic control.

leap-second-reference

Pure-reference catalog of leap-second mechanics and the bugs they cause: the 23:59:60 UTC insertion (announced ~6 months ahead by IERS Bulletin C; 27 inserted 1972-2016; abolished by 2035 per CGPM 2022), the Google/AWS leap-smear alternative, and the four bug classes a real insertion exposes - time_t non-monotonicity, negative durations, NTP cascading, and cross-node clock skew - each with a monotonic-clock fix and a freezegun simulation. Use when auditing time-sensitive code (financial timestamping, distributed logs, NTP-driven schedulers) for second-by-second progress assumptions; for the far more common daylight-saving-time transition hazards, use dst-transition-reference instead.

libfaketime-c

Wraps libfaketime (github.com/wolfcw/libfaketime), the LD_PRELOAD library that fakes the clock for any binary by intercepting time() / gettimeofday() / clock_gettime(). Covers absolute-date mode (FAKETIME='2026-12-31 23:59:00'), relative offset (FAKETIME='-1d'), advance-rate (FAKETIME='@2026-12-31 23:59:00 x5' for 5x speed), per-process scope via LD_PRELOAD, and FAKETIME_NO_CACHE for high-resolution mocking. Use when you need to fake time, mock the clock, or freeze time for C/C++ or any native binary that needs deterministic wall-clock time.

mockclock-jvm

Wraps Java's java.time.Clock + InstantSource dependency-injection pattern for testing time-sensitive code. Covers Clock.fixed(instant, zone), Clock.offset(baseClock, duration), Clock.systemDefaultZone() for production, the InstantSource interface (Java 17+), and the recommended dependency-injection pattern (constructor-inject Clock instead of calling Instant.now() directly). Use when you need to wire the clock-injection pattern (Clock.fixed, Clock.offset, MutableClock, InstantSource, Spring @Bean) into JVM (Java / Kotlin / Scala) production or test code. For pure DST transition reference (skipped or repeated hours, IANA DB, cron-double-fire bug classes) without a clock-injection need, use dst-transition-reference instead.

sinon-fake-timers-js

Wraps Sinon's standalone @sinonjs/fake-timers library for JS/TS testing: install(), tick() / tickAsync(), setSystemTime(), restore(); covers timers (setTimeout / setInterval / requestAnimationFrame), Date / performance.now() / hrtime, and the toFake option for selective override. Runner-agnostic - drives the clock directly in Mocha, AVA, Jasmine, node:test, or the browser. Use when JS/TS code needs deterministic timer or clock control and the test runner does not already expose this library behind its own built-in fake-timer API.

timecop-ruby

Wraps timecop (github.com/travisjeffery/timecop), the Ruby time-mocking gem: Timecop.freeze, Timecop.travel, Timecop.scale (time-speedup), Timecop.return (cleanup), and RSpec-friendly helpers. Use when testing Ruby/Rails code that calls Time / Date / DateTime.

timezone-test-matrix-builder

Builds a timezone, daylight saving time (DST), and leap year / leap second test matrix from wherever a codebase reads or formats dates and times. Finds time-handling code (grep for datetime / Date / Instant / time.time / timezone), sorts each spot into storage, business-logic, display, cron, or billing, picks the edge cases that matter (DST spring-forward / fall-back, ambiguous local time, leap day Feb 29, ISO 8601 / RFC 3339 round-trip, zone-database updates), and emits per-spot test stubs wired to the language's fake-clock (mock-time) library. Use when a codebase needs timezone, DST, and leap-year test coverage derived from its own date/time usage.