NOTE: After finishing this up and checking the name I found libfaketime (https://github.com/wolfcw/libfaketime) which does exactly this but better and it's not specific to Python.
timefake module adds possibility to patch current date/time in time and datetime modules to a predefined (local) date/time. Time flow will continue normally after that.
patch_from_cmdline() function will search for --set-fake-time command line argument
in YYYY-mm-ddTHH:MM:SS or 'YYYY-mm-dd HH:MM:SS' format (local time). Any "shorter"
representation (without seconds, without minute and seconds, ...) is also valid.
% cat test.py #!/usr/bin/env python from timefake import timefake timefake.patch_from_cmdline() from datetime import datetime print(datetime.now()) import time print(time.asctime()) print() % python test.py 2019-01-16 03:01:25.537577 Wed Jan 16 03:01:25 2019 % python test.py --set-fake-time '2001-01-22 23:22' 2001-01-22 23:22:00.000032 Mon Jan 22 23:22:00 2001 %
Copyright (c) 2019 Igor Brkic
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.