Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set or freeze time in python?

I want to set a fixed time using python different than that seen locally on my system , so that when I used datetime.date.today() I get to see the desired date

like image 422
Shashank Nathani Avatar asked Mar 28 '26 03:03

Shashank Nathani


1 Answers

Add argument tz_offset. See the doc https://pypi.org/project/freezegun/

from freezegun import freeze_time

@freeze_time("2012-01-14 03:21:34", tz_offset=-4)
def test():
    assert datetime.datetime.utcnow() == datetime.datetime(2012, 1, 14, 3, 21, 34)

Sometimes the asserts fail due to time zone, so adding the argument tz_offset with a constant timezone fixes that. Not fixing the timezone in tests can be a source of flaky tests because sometimes the tests will pass, but then for a short period of time the tests will fail.

like image 68
angelacpd Avatar answered Mar 31 '26 04:03

angelacpd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!