Usage

This document covers time-machine’s API.

Warning

Time is a global state. When mocking it, all concurrent threads or asynchronous functions are also affected. Some aren’t ready for time to move so rapidly or backwards, and may crash or produce unexpected results.

Also beware that other processes are not affected. For example, if you call datetime functions on a database server, they will return the real time.

Main API

class time_machine.travel(destination, *, tick=True)[source]
Parameters:
  • destination (DestinationType)

  • tick (bool)

Returns:

travel instance

travel() is a class that allows time travel, to the datetime specified by destination. It does so by mocking all functions from Python’s standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager (synchronous or asynchronous).

destination specifies the datetime to move to. It may be:

  • A datetime.datetime. If it is naive, it will have a timezone added per the current naive_mode value (which defaults to MIXED, which treats naive datetimes as UTC). If it has tzinfo set to a zoneinfo.ZoneInfo instance or datetime.UTC (datetime.timezone.utc), the current timezone will also be mocked.

  • A datetime.date. This will be converted to a datetime with the time 00:00:00, and the timezone set per the current naive_mode value (defaults to MIXED, which treats dates as UTC).

  • A datetime.timedelta. This will be interpreted relative to the current time. If already within a travel() block, the Traveller.shift() method is easier to use.

  • A float or int specifying a Unix timestamp.

  • A str. This will be parsed with datetime.fromisoformat() first, which supports ISO 8601 formats like YYYY-MM-DD and YYYY-MM-DDTHH:MM:SS. If that parsing fails and dateutil is installed, the value will be parsed with dateutil.parse(), which supports a wider variety of formats, although beware that some are ambiguous.

    In either case, if the result is naive, it will be assumed to be in local time.

Additionally, you can provide some more complex types:

  • A generator, in which case next() will be called on it, with the result treated as above.

  • A callable, in which case it will be called with no parameters, with the result treated as above.

tick defines whether time continues to “tick” after travelling, or is frozen. If True, the default, successive calls to mocked functions return values increasing by the elapsed real time since the first call. So after starting travel to 0.0 (the UNIX epoch), the first call to any datetime function will return its representation of 1970-01-01 00:00:00.000000 exactly. The following calls “tick,” so if a call was made exactly half a second later, it would return 1970-01-01 00:00:00.500000.

Mocked functions

All datetime functions in the standard library are mocked to move to the destination current datetime:

  • datetime.datetime.now()

  • datetime.datetime.utcnow()

  • time.clock_gettime() (only for CLOCK_REALTIME)

  • time.clock_gettime_ns() (only for CLOCK_REALTIME)

  • time.gmtime()

  • time.localtime()

  • time.strftime()

  • time.time()

  • time.time_ns()

The mocking is done at the C layer, replacing the function pointers for these built-ins. Therefore, it automatically affects everywhere those functions have been imported, unlike use of unittest.mock.patch().

Usage with start() / stop()

To use travel() independently, use its start() method to move to the destination time, and stop() to move back.

start()[source]
Return type:

Traveller

stop()[source]
Return type:

None

For example:

import datetime as dt
import time_machine

traveller = time_machine.travel(dt.datetime(1985, 10, 26))
traveller.start()
# It's the past!
assert dt.date.today() == dt.date(1985, 10, 26)
traveller.stop()
# We've gone back to the future!
assert dt.date.today() > dt.date(2020, 4, 29)

travel() instances are nestable, but you’ll need to be careful when manually managing to call their stop() methods in the correct order, even when exceptions occur. It’s recommended to use the decorator or context manager forms instead, to take advantage of Python features to do this.

Function decorator

When used as a function decorator, time is mocked during the wrapped function’s duration:

import time
import time_machine


@time_machine.travel("1970-01-01 00:00 +0000")
def test_in_the_deep_past():
    assert 0.0 < time.time() < 1.0

You can also decorate asynchronous functions (coroutines):

import time
import time_machine


@time_machine.travel("1970-01-01 00:00 +0000")
async def test_in_the_deep_past():
    assert 0.0 < time.time() < 1.0

Context manager

When used as a context manager, time is mocked during the with block. This works both synchronously:

import time
import time_machine


def test_in_the_deep_past():
    with time_machine.travel(0.0):
        assert 0.0 < time.time() < 1.0

…and asynchronously:

import time
import time_machine


async def test_in_the_deep_past():
    async with time_machine.travel(0.0):
        assert 0.0 < time.time() < 1.0

Class decorator

Only unittest.TestCase subclasses are supported. When applied as a class decorator to such classes, time is mocked from the start of setUpClass() to the end of tearDownClass():

import time
import time_machine
import unittest


@time_machine.travel(0.0)
class DeepPastTests(TestCase):
    def test_in_the_deep_past(self):
        assert 0.0 < time.time() < 1.0

Note this is different to unittest.mock.patch()'s behaviour, which is to mock only during the test methods. For pytest-style test classes, see the autouse fixture pattern in the pytest plugin documentation.

Timezone mocking

If the destination passed to time_machine.travel() or Traveller.move_to() has its tzinfo set to a zoneinfo.ZoneInfo instance, the current timezone will be mocked. This will be done by calling time.tzset(), so it is only available on Unix.

time.tzset() changes the time module’s timezone constants and features that rely on those, such as time.localtime(). It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with its timezone.override()).

Here’s a worked example changing the current timezone:

import datetime as dt
import time
from zoneinfo import ZoneInfo
import time_machine

hill_valley_tz = ZoneInfo("America/Los_Angeles")


@time_machine.travel(dt.datetime(2015, 10, 21, 16, 29, tzinfo=hill_valley_tz))
def test_hoverboard_era():
    assert time.tzname == ("PST", "PDT")
    now = dt.datetime.now()
    assert (now.hour, now.minute) == (16, 29)
class time_machine.Traveller(destination_timestamp, destination_tzname, tick)[source]

The start() method and entry of the context manager both return a Traveller object that corresponds to the given “trip” in time. This has a couple methods that can be used to travel to other times.

Parameters:
  • destination_timestamp (float)

  • destination_tzname (str | None)

  • tick (bool)

move_to(destination, tick=None)[source]
Parameters:
  • destination (int | float | datetime | timedelta | date | str | Callable[[], int | float | datetime | timedelta | date | str] | Generator[int | float | datetime | timedelta | date | str, None, None])

  • tick (bool | None)

Return type:

None

move_to() moves the current time to a new destination. destination may be any of the types supported by travel.

tick may be set to a boolean, to change the tick flag of travel.

For example:

import datetime as dt
import time
import time_machine

with time_machine.travel(0, tick=False) as traveller:
    assert time.time() == 0

    traveller.move_to(234)
    assert time.time() == 234
shift(delta)[source]
Parameters:

delta (timedelta | int | float)

Return type:

None

shift() takes one argument, delta, which moves the current time by the given offset. delta may be a timedelta or a number of seconds, which will be added to destination. It may be negative, in which case time will move to an earlier point.

For example:

import datetime as dt
import time
import time_machine

with time_machine.travel(0, tick=False) as traveller:
    assert time.time() == 0

    traveller.shift(dt.timedelta(seconds=100))
    assert time.time() == 100

    traveller.shift(-dt.timedelta(seconds=10))
    assert time.time() == 90
time_machine.naive_mode

The naive_mode attribute controls how naive datetimes are interpreted. It takes a value from the NaiveMode enum:

class time_machine.NaiveMode[source]
MIXED

Naive datetime objects and date objects are interpreted as UTC. Naive datetime strings are interpreted as local time.

This mode is the default for backward compatibility with existing behaviour.

UTC

Naive datetimes are interpreted as UTC, regardless of input type.

This mode provides consistency across all input types, but is inconsistent with Python’s default behaviour for naive datetimes.

LOCAL

All naive datetimes are interpreted as local time.

This mode represents Python’s default behaviour for naive datetimes, as well as how freezegun interprets them. It’s especially useful when migrating tests from freezegun to time-machine.

ERROR

Using a naive datetime raises a RuntimeError. This includes dt.date objects, as they do not have timezone information.

This mode prevents your test suite from changing meaning depending on the timezone of the machine it is run on. Use it for maximum reproducibility.

To use a different mode, set the time_machine.naive_mode attribute to your chosen value, like:

import time_machine

time_machine.naive_mode = time_machine.NaiveMode.LOCAL

This is probably best done at the start of your test suite, such as within module-level code in a pytest conftest.py file.

To temporarily set a different mode, use unittest.mock.patch.object():

from unittest import mock
import time_machine

with mock.patch.object(time_machine, "naive_mode", time_machine.NaiveMode.ERROR):
    # Code within this block will use the ERROR mode
    with time_machine.travel(...):
        ...

Escape hatch API

time_machine.escape_hatch = <time_machine._EscapeHatch object>

The escape_hatch object provides functions to bypass time-machine, calling the real datetime functions, without any mocking. It also provides a way to check if time-machine is currently time travelling.

These capabilities are useful in rare circumstances. For example, if you need to authenticate with an external service during time travel, you may need the real value of datetime.now(). When not time-travelling, these functions (except is_travelling()) raise ValueError to avoid accidental use.

The functions are:

  • escape_hatch.is_travelling() -> bool

    Returns True if time_machine.travel() is active, False otherwise.

  • escape_hatch.datetime.datetime.now()

    Wraps the real datetime.datetime.now().

  • escape_hatch.datetime.datetime.utcnow()

    Wraps the real datetime.datetime.utcnow().

  • escape_hatch.time.clock_gettime()

    Wraps the real time.clock_gettime().

  • escape_hatch.time.clock_gettime_ns()

    Wraps the real time.clock_gettime_ns().

  • escape_hatch.time.gmtime()

    Wraps the real time.gmtime().

  • escape_hatch.time.localtime()

    Wraps the real time.localtime().

  • escape_hatch.time.strftime()

    Wraps the real time.strftime().

  • escape_hatch.time.time()

    Wraps the real time.time().

  • escape_hatch.time.time_ns()

    Wraps the real time.time_ns().

For example:

import time_machine


with time_machine.travel(...):
    if time_machine.escape_hatch.is_travelling():
        print("We need to go back to the future!")

    real_now = time_machine.escape_hatch.datetime.datetime.now()
    external_authenticate(now=real_now)