4

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
jamis0n
  • 3,610
  • 8
  • 34
  • 50
  • The input is interpreted as UTC time. You should get the correct `time.time()` value in `.utcnow()` case. I can't reproduce it using `TZ=America/Los_Angeles` (no 1 hour offset). `freezegun`'s default utc offset for the local timezone is zero (`tz_offset` parameter) for `datetime.now()` method and therefore `.utcnow() == .now()` is expected. – jfs Jul 08 '15 at 23:16
  • 1
    Unrelated: [`freezegun` uses `-time.timezone` as a utc offset for `time.localtime()` function](https://github.com/spulec/freezegun/blob/a6d4fb6f627ff115302a5d0e00f78b70431d289f/freezegun/api.py#L38). It is inconsistent i.e., `.utcnow() == .now()` but `gmtime() != localtime()` unless `tz_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](http://stackoverflow.com/questions/3168096/getting-computers-utc-offset-in-python). – jfs Jul 08 '15 at 23:17

0 Answers0