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

孤人 提交于 2019-12-10 20:15:35

问题


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

来源:https://stackoverflow.com/questions/31296798/python-freezegun-giving-different-values-when-freezing-time-to-datetime-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!