Python Freezegun giving different values when freezing time to datetime.datetime.now()
Asked Answered
C

0

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
Comma answered 8/7, 2015 at 15:13 Comment(2)
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.Renovate
Unrelated: freezegun uses -time.timezone as a utc offset for time.localtime() function. 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.Renovate

© 2022 - 2024 — McMap. All rights reserved.