or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-migration.mdcore-time-travel.mdescape-hatch.mdindex.mdpytest-integration.md

index.mddocs/

0

# Time Machine

1

2

A Python library for mocking time in tests, enabling developers to travel through time to create deterministic tests for time-sensitive code. Time Machine patches Python's time and datetime functions at the C level for high performance and comprehensive coverage.

3

4

## Package Information

5

6

- **Package Name**: time-machine

7

- **Language**: Python

8

- **Installation**: `pip install time-machine`

9

- **Python Version**: 3.9+

10

11

## Core Imports

12

13

```python

14

import time_machine

15

```

16

17

Common usage pattern:

18

19

```python

20

from time_machine import travel

21

```

22

23

## Basic Usage

24

25

```python

26

import time_machine

27

from datetime import datetime, timezone

28

29

# Context manager usage

30

with time_machine.travel(datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc)):

31

print(datetime.now()) # Prints 2023-01-01 12:00:00

32

33

# Decorator usage

34

@time_machine.travel("2023-01-01 12:00 UTC")

35

def test_something():

36

assert datetime.now().year == 2023

37

38

# Moving through time during travel

39

with time_machine.travel(0) as traveller:

40

print(datetime.now()) # 1970-01-01 00:00:00

41

traveller.shift(3600) # Add 1 hour

42

print(datetime.now()) # 1970-01-01 01:00:00

43

traveller.move_to("2023-01-01")

44

print(datetime.now()) # 2023-01-01 00:00:00

45

```

46

47

## Architecture

48

49

Time Machine operates by patching Python's time-related functions at the C extension level:

50

51

- **C Extension**: `_time_machine.c` provides low-level patching of time functions

52

- **Coordinates System**: Manages time travel state with support for nested time travel

53

- **Escape Hatch**: Provides access to real time functions during time travel

54

- **Pytest Integration**: Automatic fixture and marker support for seamless test integration

55

56

The patching system ensures that all time-related functions (`time.time()`, `datetime.now()`, etc.) return consistent mocked values during time travel, with support for both static time (tick=False) and advancing time (tick=True).

57

58

## Capabilities

59

60

### Core Time Travel

61

62

Primary time travel functionality using the `travel` class as a context manager or decorator. Supports various destination formats including timestamps, datetime objects, ISO strings, and relative time deltas.

63

64

```python { .api }

65

class travel:

66

def __init__(self, destination: DestinationType, *, tick: bool = True): ...

67

def start(self) -> Coordinates: ...

68

def stop(self) -> None: ...

69

def __enter__(self) -> Coordinates: ...

70

def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...

71

async def __aenter__(self) -> Coordinates: ...

72

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...

73

```

74

75

```python { .api }

76

class Coordinates:

77

def time(self) -> float: ...

78

def time_ns(self) -> int: ...

79

def shift(self, delta: dt.timedelta | int | float) -> None: ...

80

def move_to(self, destination: DestinationType, tick: bool | None = None) -> None: ...

81

```

82

83

[Core Time Travel](./core-time-travel.md)

84

85

### Pytest Integration

86

87

Seamless integration with pytest through fixtures, markers, and automatic test discovery. Provides both imperative and declarative approaches to time travel in tests.

88

89

```python { .api }

90

class TimeMachineFixture:

91

def move_to(self, destination: DestinationType, tick: bool | None = None) -> None: ...

92

def shift(self, delta: dt.timedelta | int | float) -> None: ...

93

def stop(self) -> None: ...

94

```

95

96

```python { .api }

97

@pytest.fixture(name="time_machine")

98

def time_machine_fixture(request: pytest.FixtureRequest) -> Generator[TimeMachineFixture, None, None]: ...

99

```

100

101

[Pytest Integration](./pytest-integration.md)

102

103

### Escape Hatch

104

105

Access to real time functions during time travel for testing time-dependent operations that need actual system time, such as performance measurements or external API calls.

106

107

```python { .api }

108

class _EscapeHatch:

109

def is_travelling(self) -> bool: ...

110

time: _EscapeHatchTime

111

datetime: _EscapeHatchDatetime

112

```

113

114

```python { .api }

115

escape_hatch: _EscapeHatch

116

```

117

118

[Escape Hatch](./escape-hatch.md)

119

120

### CLI Migration Tool

121

122

Command-line tool for migrating test code from freezegun to time-machine, automatically rewriting imports and function calls.

123

124

```python { .api }

125

def main(argv: Sequence[str] | None = None) -> int: ...

126

def migrate_files(files: list[str]) -> int: ...

127

def migrate_file(filename: str) -> int: ...

128

```

129

130

[CLI Migration Tool](./cli-migration.md)

131

132

## Type Definitions

133

134

```python { .api }

135

DestinationBaseType = Union[

136

int, # Unix timestamp

137

float, # Unix timestamp with fractional seconds

138

dt.datetime, # Datetime object (timezone-aware recommended)

139

dt.timedelta, # Relative time from current time

140

dt.date, # Date (converted to midnight UTC)

141

str, # ISO 8601 datetime string

142

]

143

144

DestinationType = Union[

145

DestinationBaseType,

146

Callable[[], DestinationBaseType], # Function returning destination

147

Generator[DestinationBaseType, None, None], # Generator yielding destinations

148

]

149

150

_TimeTuple = tuple[int, int, int, int, int, int, int, int, int] # Time tuple format used by time functions

151

```

152

153

## Constants

154

155

```python { .api }

156

NANOSECONDS_PER_SECOND: int = 1_000_000_000

157

SYSTEM_EPOCH_TIMESTAMP_NS: int # System epoch timestamp in nanoseconds (Windows compatibility)

158

escape_hatch: _EscapeHatch

159

```