Add microsecond support to timeutils.utcnow_ts()
Now we have the ability to generate a timestamp with microseconds. Change-Id: I34d51b71c01df02bef46639149fde08f89f0e110 Signed-off-by: Paul Belanger <paul.belanger@polybeacon.com>
This commit is contained in:
@@ -93,14 +93,23 @@ def is_newer_than(after, seconds):
|
|||||||
return after - utcnow() > datetime.timedelta(seconds=seconds)
|
return after - utcnow() > datetime.timedelta(seconds=seconds)
|
||||||
|
|
||||||
|
|
||||||
def utcnow_ts():
|
def utcnow_ts(microsecond=False):
|
||||||
"""Timestamp version of our utcnow function."""
|
"""Timestamp version of our utcnow function."""
|
||||||
if utcnow.override_time is None:
|
if utcnow.override_time is None:
|
||||||
# NOTE(kgriffs): This is several times faster
|
# NOTE(kgriffs): This is several times faster
|
||||||
# than going through calendar.timegm(...)
|
# than going through calendar.timegm(...)
|
||||||
return int(time.time())
|
timestamp = time.time()
|
||||||
|
if not microsecond:
|
||||||
|
timestamp = int(timestamp)
|
||||||
|
return timestamp
|
||||||
|
|
||||||
return calendar.timegm(utcnow().timetuple())
|
now = utcnow()
|
||||||
|
timestamp = calendar.timegm(now.timetuple())
|
||||||
|
|
||||||
|
if microsecond:
|
||||||
|
timestamp += float(now.microsecond) / 1000000
|
||||||
|
|
||||||
|
return timestamp
|
||||||
|
|
||||||
|
|
||||||
def utcnow():
|
def utcnow():
|
||||||
|
|||||||
@@ -160,6 +160,22 @@ class TimeUtilsTest(test_base.BaseTestCase):
|
|||||||
ts = timeutils.utcnow_ts()
|
ts = timeutils.utcnow_ts()
|
||||||
self.assertEqual(ts, skynet_self_aware_ts)
|
self.assertEqual(ts, skynet_self_aware_ts)
|
||||||
|
|
||||||
|
def test_utcnow_ts_microsecond(self):
|
||||||
|
skynet_self_aware_ts = 872835240.000123
|
||||||
|
skynet_dt = datetime.datetime.utcfromtimestamp(skynet_self_aware_ts)
|
||||||
|
self.assertEqual(self.skynet_self_aware_ms_time, skynet_dt)
|
||||||
|
|
||||||
|
# NOTE(kgriffs): timeutils.utcnow_ts() uses time.time()
|
||||||
|
# IFF time override is not set.
|
||||||
|
with mock.patch('time.time') as time_mock:
|
||||||
|
time_mock.return_value = skynet_self_aware_ts
|
||||||
|
ts = timeutils.utcnow_ts(microsecond=True)
|
||||||
|
self.assertEqual(ts, skynet_self_aware_ts)
|
||||||
|
|
||||||
|
timeutils.set_time_override(skynet_dt)
|
||||||
|
ts = timeutils.utcnow_ts(microsecond=True)
|
||||||
|
self.assertEqual(ts, skynet_self_aware_ts)
|
||||||
|
|
||||||
def test_utcnow(self):
|
def test_utcnow(self):
|
||||||
timeutils.set_time_override(mock.sentinel.utcnow)
|
timeutils.set_time_override(mock.sentinel.utcnow)
|
||||||
self.assertEqual(timeutils.utcnow(), mock.sentinel.utcnow)
|
self.assertEqual(timeutils.utcnow(), mock.sentinel.utcnow)
|
||||||
|
|||||||
Reference in New Issue
Block a user