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:
travelinstance
travel()is a class that allows time travel, to the datetime specified bydestination. 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).destinationspecifies the datetime to move to. It may be:A
datetime.datetime. If it is naive, it will have a timezone added per the currentnaive_modevalue (which defaults toMIXED, which treats naive datetimes as UTC). If it hastzinfoset to azoneinfo.ZoneInfoinstance ordatetime.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 currentnaive_modevalue (defaults to MIXED, which treats dates as UTC).A
datetime.timedelta. This will be interpreted relative to the current time. If already within atravel()block, theTraveller.shift()method is easier to use.A
floatorintspecifying a Unix timestamp.A
str. This will be parsed withdatetime.fromisoformat()first, which supports ISO 8601 formats likeYYYY-MM-DDandYYYY-MM-DDTHH:MM:SS. If that parsing fails and dateutil is installed, the value will be parsed withdateutil.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.
tickdefines whether time continues to “tick” after travelling, or is frozen. IfTrue, the default, successive calls to mocked functions return values increasing by the elapsed real time since the first call. So after starting travel to0.0(the UNIX epoch), the first call to any datetime function will return its representation of1970-01-01 00:00:00.000000exactly. The following calls “tick,” so if a call was made exactly half a second later, it would return1970-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 forCLOCK_REALTIME)time.clock_gettime_ns()(only forCLOCK_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 itsstart()method to move to the destination time, andstop()to move back.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 theirstop()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
withblock. 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.TestCasesubclasses are supported. When applied as a class decorator to such classes, time is mocked from the start ofsetUpClass()to the end oftearDownClass():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
destinationpassed totime_machine.travel()orTraveller.move_to()has itstzinfoset to azoneinfo.ZoneInfoinstance, the current timezone will be mocked. This will be done by callingtime.tzset(), so it is only available on Unix.time.tzset()changes thetimemodule’s timezone constants and features that rely on those, such astime.localtime(). It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with itstimezone.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 aTravellerobject 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.destinationmay be any of the types supported bytravel.tickmay be set to a boolean, to change thetickflag oftravel.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()takes one argument,delta, which moves the current time by the given offset.deltamay be atimedeltaor 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_modeattribute controls how naive datetimes are interpreted. It takes a value from theNaiveModeenum:- class time_machine.NaiveMode[source]¶
- MIXED¶
Naive
datetimeobjects anddateobjects 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 includesdt.dateobjects, 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_modeattribute 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.pyfile.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() -> boolReturns
Trueiftime_machine.travel()is active,Falseotherwise.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)