Im trying to use freezegun to set the clock back 10 seconds for a unit test.
I've found that setting the time to now with freezegun results in the expected behavior for datetime.datetime.now() but somewhat different behavior for time.time() in that the "frozen" time is ~30,000 seconds behind (8 hours).
Using datetime.datetime.utcnow(), its off by 3600 seconds (1 hour).
What do I need to do to appropriately mock the time to be used with time.time()?
Using now(): 8 hours off
def test_freezegun(self):
""" Test that freezegun can set time.time() back 10 seconds. """
with freezegun.freeze_time(datetime.datetime.now()):
print time.time()
print datetime.datetime.now()
print time.time()
print datetime.datetime.now()
# Output
[08:09:32] 1436339372
[08:09:32] 2015-07-08 08:09:32.119516
[08:09:32] 1436368172
[08:09:32] 2015-07-08 08:09:32.175031
Using utcnow(): 1 hour off
def test_freezegun(self):
""" Test that freezegun can set time.time() back 10 seconds. """
with freezegun.freeze_time(datetime.datetime.utcnow()):
print time.time()
print datetime.datetime.now()
print time.time()
print datetime.datetime.now()
# Output
[08:08:56] 1436364536
[08:08:56] 2015-07-08 15:08:56.589202
[08:08:56] 1436368136
[08:08:56] 2015-07-08 08:08:56.655346
UPDATE:
This works, but I'd like to understand why:
Using utcnow() + 1 hour: identical time.time() output, as expected
def test_freezegun(self):
""" Test that freezegun can set time.time() back 10 seconds. """
with freezegun.freeze_time(datetime.datetime.utcnow() + datetime.timedelta(hours=1)):
print time.time()
print datetime.datetime.now()
print time.time()
print datetime.datetime.now()
#Output
[08:22:27] 1436368947
[08:22:27] 2015-07-08 16:22:27.268315
[08:22:27] 1436368947
[08:22:27] 2015-07-08 08:22:27.339116
time.time()
value in.utcnow()
case. I can't reproduce it usingTZ=America/Los_Angeles
(no 1 hour offset).freezegun
's default utc offset for the local timezone is zero (tz_offset
parameter) fordatetime.now()
method and therefore.utcnow() == .now()
is expected. – Renovatefreezegun
uses-time.timezone
as a utc offset fortime.localtime()
function. It is inconsistent i.e.,.utcnow() == .now()
butgmtime() != localtime()
unlesstz_offset=-time.timezone
. Anyway, it is incorrect to use-time.timezone
as a utc offset unconditionaly e.g., it does not take into account DST. – Renovate