Mock datetime with time-machine in Python

Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Requires third-party packages — install first
pip install time-machine

Python code

11 lines
Python 3.9+
from time_machine import travel
from datetime import datetime


@travel("2020-01-01 10:30:00")
def check_date():
    return datetime.utcnow()


if __name__ == "__main__":
    print(check_date())

Output

stdout
2020-01-01 10:30:00

How it works

The @travel decorator shifts the system time for the decorated function's execution. Inside check_date, datetime.utcnow() returns the mocked time instead of the real current time. This is a lightweight alternative to freezegun and supports Python's datetime module directly. The mock is automatically restored after the function exits.

Common mistakes

  • Forgetting to install time-machine with pip install time-machine
  • Using datetime.now() instead of datetime.utcnow() and expecting UTC
  • Applying the decorator to the wrong scope — it must wrap the function that checks the time
  • Not accounting for timezone-aware code that uses timezone.utc

Variations

  1. Use `@travel('2020-01-01 10:30:00', tz_offset=0)` for timezone-explicit tests

Real-world use cases

  • Writing unit tests for code that logs timestamps, ensuring deterministic output.
  • Validating date-handling logic without waiting for a specific real time to arrive.
  • Reproducing a time-sensitive bug by freezing the clock to the exact moment it occurs.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.