$ show adamchainz/time-machine
The time-machine library is a Python package designed to mock system time in tests by patching the datetime and time modules at the C level. It provides a versatile API that can be used as a context manager, decorator, or pytest fixture, allowing developers to set a fixed time or simulate time progression. The library supports timezone handling, nesting of time travel contexts, and an escape hatch to access the real time when needed. Additionally, it includes a command-line tool to assist in migrating from the popular freezegun library. The core innovation lies in the C extension (_time_machine.c), which directly manipulates the function pointers of the datetime and time modules to replace them with custom implementations. This approach ensures high performance and comprehensive mocking, affecting all references to these functions throughout the Python process. The Python layer manages the state of active time travels, handles timezone settings via the TZ environment variable, and provides a rich set of features for controlling the simulated time, such as moving to different timestamps or shifting by a delta. The project demonstrates strong engineering practices with comprehensive test coverage, modern development tooling (including pre-commit hooks, linting, and type checking), and careful consideration of cross-platform compatibility. It maintains backward compatibility while introducing improvements, such as making the dateutil dependency optional and adding controls for interpreting naive datetime values. The CLI tool for migration showcases a practical use of the tokenize_rt library for precise source code transformations, reflecting attention to real-world usability.
The LLM identified 1 files worth highlighting for reuse:
This function converts a variety of date/time inputs (int, float, datetime, timedelta, date, string, callable, generator) into a Unix timestamp and an optional timezone name. It handles timezone-naive inputs according to a configurable naive mode (UTC, local, or error) and provides a fallback to python-dateutil for string parsing. This pattern demonstrates robust input handling for date/time values, making it suitable for reuse in other applications that need to accept flexible date/time specifications. With minor adjustments (such as parameterizing the naive mode and internalizing the dateutil check), it could be extracted into a standalone utility.