Skip to content

Commit 9e0d797

Browse files
committed
journal: convert seek_realtime argument to microseconds
This somewhat breaks backwards compatibility, but not for the previously documented arguments: floats are now interpreted differently, but ints and datetime.datetime objects are interpreted the same as before. But the documentation clearly stated that only ints and datetime.datetime objects were allowed. This makes seek_realtime match seek_monotonic and other functions which take time and follows the principle of least surprise. Fixes #21.
1 parent 5211952 commit 9e0d797

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

systemd/journal.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -298,14 +298,25 @@ def wait(self, timeout=None):
298298
return super(Reader, self).wait(us)
299299

300300
def seek_realtime(self, realtime):
301-
"""Seek to a matching journal entry nearest to `realtime` time.
301+
"""Seek to a matching journal entry nearest to `timestamp` time.
302302
303-
Argument `realtime` must be either an integer unix timestamp or
304-
datetime.datetime instance.
303+
Argument `realtime` must be either an integer UNIX timestamp (in
304+
microseconds since the beginning of the UNIX epoch), or an float UNIX
305+
timestamp (in seconds since the beginning of the UNIX epoch), or a
306+
datetime.datetime instance. The integer form is deprecated.
307+
308+
>>> import time
309+
>>> from systemd import journal
310+
311+
>>> yesterday = time.time() - 24 * 60**2
312+
>>> j = journal.Reader()
313+
>>> j.seek_realtime(yesterday)
305314
"""
306315
if isinstance(realtime, _datetime.datetime):
307-
realtime = float(realtime.strftime("%s.%f")) * 1000000
308-
return super(Reader, self).seek_realtime(int(realtime))
316+
realtime = int(float(realtime.strftime("%s.%f")) * 1000000)
317+
elif not isinstance(realtime, int):
318+
realtime = int(realtime * 1000000)
319+
return super(Reader, self).seek_realtime(realtime)
309320

310321
def seek_monotonic(self, monotonic, bootid=None):
311322
"""Seek to a matching journal entry nearest to `monotonic` time.

systemd/test/test_journal.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1-
import logging
21
import contextlib
3-
import uuid
2+
import datetime
43
import errno
4+
import logging
55
import os
6+
import time
7+
import uuid
8+
69
from systemd import journal, id128
710

811
import pytest
@@ -176,3 +179,14 @@ def test_reader_convert_entry(tmpdir):
176179
'y1' : b'\200\200',
177180
'x2' : ['YYY', 'YYY'],
178181
'y2' : [b'\200\200', b'\200\201']}
182+
183+
def test_seek_realtime(tmpdir):
184+
j = journal.Reader(path=tmpdir.strpath)
185+
186+
now = time.time()
187+
j.seek_realtime(now)
188+
189+
j.seek_realtime(12345)
190+
191+
long_ago = datetime.datetime(1970, 5, 4)
192+
j.seek_realtime(long_ago)

0 commit comments

Comments
 (0)