Add UTC-aware timestamp format with usec precision
- Replaced time.ctime(), which formats time in local timezone with only
seconds-level precision, with strftime(...) from datetime module to
enable formatting with full microsecond precision and control over
time zone representation.
- Defaulted the time to display in UTC.
- Introduced --localtime command-line option to print timestamp in
local timezone.
- Ensured timestamps match journalctl -o short-precise format
(e.g., Jun 10 04:53:00.966670).
Change-Id: I468c980ab9e3d9aaa391bb7ec6d663e6448b14ff
Signed-off-by: Manojkiran Eda <manojkiran.eda@gmail.com>
diff --git a/pretty-journal/pretty-journal.py b/pretty-journal/pretty-journal.py
index 7cf4415..2e7bbb5 100755
--- a/pretty-journal/pretty-journal.py
+++ b/pretty-journal/pretty-journal.py
@@ -6,10 +6,11 @@
will convert that json output into the standard journalctl output
"""
+import datetime
import json
import re
-import time
from argparse import ArgumentParser
+from datetime import timezone
def jpretty_to_python(buf):
@@ -21,12 +22,24 @@
return entries
+def format_timestamp_utc(us_timestamp, use_utc=False):
+ """Convert microseconds since epoch to formatted timestamp (with microseconds)."""
+ ts = float(us_timestamp) / 1000000
+ tz = timezone.utc if use_utc else None
+ dt = datetime.datetime.fromtimestamp(ts, tz)
+ return dt.strftime("%b %d %H:%M:%S.%f")
+
+
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"journalfile", metavar="FILE", help="the file to parse"
)
-
+ parser.add_argument(
+ "--localtime",
+ action="store_true",
+ help="Display timestamps in local time (default is UTC)",
+ )
args = parser.parse_args()
with open(args.journalfile) as fd:
@@ -34,7 +47,9 @@
entries = sorted(entries, key=lambda k: k["__REALTIME_TIMESTAMP"])
for e in entries:
- e["ts"] = time.ctime(float(e["__REALTIME_TIMESTAMP"]) / 1000000)
+ e["ts"] = format_timestamp_utc(
+ e["__REALTIME_TIMESTAMP"], use_utc=not args.localtime
+ )
try:
print(
f'{e["ts"]} {e["_HOSTNAME"]} {e["SYSLOG_IDENTIFIER"]}:'