Skip to content

Commit

Permalink
journal: fix compatibility with python2
Browse files Browse the repository at this point in the history
This is a lazy workaround: 4c9a241
is amended to do nothing on python2, so we have the same issue that
was present before. This allows the code to execute, and hopefully
almost nobody is using python2 code anyway.

f868a56 is amended in the same way.
For python2 code we have the same lack of timezone-awareness as before.

This allows the tests to pass under python 2.7.
  • Loading branch information
keszybz committed Aug 16, 2022
1 parent 6320847 commit 872ce30
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
13 changes: 11 additions & 2 deletions systemd/journal.py
Expand Up @@ -51,7 +51,10 @@ def _convert_monotonic(m):
def _convert_source_monotonic(s):
return _datetime.timedelta(microseconds=int(s))

_LOCAL_TIMEZONE = _datetime.datetime.now().astimezone().tzinfo
try:
_LOCAL_TIMEZONE = _datetime.datetime.now().astimezone().tzinfo
except TypeError:
_LOCAL_TIMEZONE = None

def _convert_realtime(t):
return _datetime.datetime.fromtimestamp(t / 1000000, _LOCAL_TIMEZONE)
Expand Down Expand Up @@ -313,7 +316,13 @@ def seek_realtime(self, realtime):
>>> j.seek_realtime(yesterday)
"""
if isinstance(realtime, _datetime.datetime):
realtime = int(float(realtime.astimezone().strftime("%s.%f")) * 1000000)
try:
realtime = realtime.astimezone()
except TypeError:
# With python2: Required argument 'tz' (pos 1) not found
pass

realtime = int(float(realtime.strftime("%s.%f")) * 1000000)
elif not isinstance(realtime, int):
realtime = int(realtime * 1000000)
return super(Reader, self).seek_realtime(realtime)
Expand Down
10 changes: 7 additions & 3 deletions systemd/test/test_journal.py
Expand Up @@ -6,6 +6,7 @@
import os
import time
import uuid
import sys
import traceback as _traceback

from systemd import journal, id128
Expand Down Expand Up @@ -294,13 +295,16 @@ def test_reader_convert_timestamps(tmpdir):
j = journal.Reader(path=tmpdir.strpath)

val = j._convert_field('_SOURCE_REALTIME_TIMESTAMP', 1641651559324187)
assert val.tzinfo is not None
if sys.version_info >= (3,):
assert val.tzinfo is not None

val = j._convert_field('__REALTIME_TIMESTAMP', 1641651559324187)
assert val.tzinfo is not None
if sys.version_info >= (3,):
assert val.tzinfo is not None

val = j._convert_field('COREDUMP_TIMESTAMP', 1641651559324187)
assert val.tzinfo is not None
if sys.version_info >= (3,):
assert val.tzinfo is not None

def test_seek_realtime(tmpdir):
j = journal.Reader(path=tmpdir.strpath)
Expand Down

0 comments on commit 872ce30

Please sign in to comment.