Created
March 31, 2026 06:19
-
-
Save jnturton/7a70e5a4425af2c048920cbd37b658fb to your computer and use it in GitHub Desktop.
Extract a timestamp from a 20 hex digit Db2 LRSN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| Db2 z/OS LRSN Decoder | |
| ===================== | |
| LRSN structure (10 bytes / 20 hex digits): | |
| Byte 1 : Log stream identifier / prefix (0x00 for a single log stream) | |
| Bytes 2-9 : Timestamp — 8 bytes of a 64-bit IBM TOD (STCK) clock value, big endian | |
| Byte 10 : Uniqueness / sequence counter | |
| IBM TOD clock encoding: | |
| The 64-bit STCK value has a unit of 2^-12 microseconds (1/4096 µs). | |
| To decode: | |
| full_tod = 8 byte value as big endian # convert hex to bytes, bytes to int using big endian | |
| microsecs = full_tod / 4096 # convert ticks of 2^-12 to microseconds | |
| datetime = epoch + timedelta(microseconds=microsecs) | |
| where epoch = 1900-01-01 00:00:00 UTC | |
| Copyright 2026 James Turton | |
| Licensed under the Apache License, Version 2.0 (the "License"); | |
| you may not use this file except in compliance with the License. | |
| You may obtain a copy of the License at | |
| http://www.apache.org/licenses/LICENSE-2.0 | |
| Unless required by applicable law or agreed to in writing, software | |
| distributed under the License is distributed on an "AS IS" BASIS, | |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| See the License for the specific language governing permissions and | |
| limitations under the License. | |
| """ | |
| from datetime import datetime, timedelta, timezone | |
| EPOCH = datetime(1900, 1, 1, tzinfo=timezone.utc) | |
| def decode_lrsn(lrsn_hex: str) -> dict: | |
| """ | |
| Decode a Db2 z/OS LRSN (20 hex digit string). | |
| Returns a dict with: | |
| - lrsn : original LRSN string (uppercased) | |
| - prefix_byte : hex string of byte 1 (log stream identifier) | |
| - timestamp_hex : hex string of bytes 2-9 (8-byte TOD fragment) | |
| - sequence_hex : hex string of byte 10 (uniqueness counter) | |
| - full_tod : reconstructed 64-bit TOD value | |
| - microseconds : microseconds since 1900-01-01 (full_tod / 4096) | |
| - datetime_utc : decoded datetime (UTC) | |
| """ | |
| lrsn_hex = lrsn_hex.strip().upper().replace(" ", "") | |
| if len(lrsn_hex) != 20: | |
| raise ValueError(f"LRSN must be exactly 20 hex digits, got {len(lrsn_hex)}") | |
| if not all(c in "0123456789ABCDEF" for c in lrsn_hex): | |
| raise ValueError("LRSN must contain only hex digits (0-9, A-F)") | |
| prefix_hex = lrsn_hex[0:2] # byte 1 | |
| timestamp_hex = lrsn_hex[2:18] # bytes 2-9 (8 bytes = 16 hex digits) | |
| sequence_hex = lrsn_hex[18:20] # byte 10 | |
| full_tod = int.from_bytes(bytes.fromhex(timestamp_hex), byteorder="big") | |
| # IBM TOD unit = 2^-12 µs, so divide by 4096 to get microseconds | |
| microseconds = full_tod / 4096 | |
| dt_utc = EPOCH + timedelta(microseconds=microseconds) | |
| return { | |
| "lrsn": lrsn_hex, | |
| "prefix_byte": prefix_hex, | |
| "timestamp_hex": timestamp_hex, | |
| "sequence_hex": sequence_hex, | |
| "full_tod": full_tod, | |
| "microseconds": microseconds, | |
| "datetime_utc": dt_utc, | |
| } | |
| def pretty_print(result: dict) -> None: | |
| print("=" * 62) | |
| print(" Db2 z/OS LRSN Decoder") | |
| print("=" * 62) | |
| print(f" Full LRSN : {result['lrsn']}") | |
| print(f" Prefix byte : {result['prefix_byte']}") | |
| print(f" Timestamp (bytes 2-9): {result['timestamp_hex']}") | |
| print(f" Sequence (byte 10) : {result['sequence_hex']}") | |
| print("-" * 62) | |
| print(f" Full TOD : {result['full_tod']}") | |
| print(f" Microseconds : {result['microseconds']:,.3f}") | |
| print("-" * 62) | |
| dt = result["datetime_utc"] | |
| print(f" Decoded timestamp : {dt.strftime('%Y-%m-%d %H:%M:%S.%f')} UTC") | |
| print(f" Formatted : {dt.strftime('%A, %d %B %Y %H:%M:%S UTC')}") | |
| print("=" * 62) | |
| if __name__ == "__main__": | |
| import sys | |
| if len(sys.argv) != 2: | |
| print( | |
| f"Usage: {sys.argv[0]} 20_hex_digit_LRSN. Unit test: pytest decode_lrsn.py" | |
| ) | |
| sys.exit(2) | |
| lrsn_input = sys.argv[1] | |
| try: | |
| result = decode_lrsn(lrsn_input) | |
| pretty_print(result) | |
| sys.exit(0) # avoid continuing to the unit test code below | |
| except ValueError as e: | |
| print(f"Error: {e}", file=sys.stderr) | |
| sys.exit(1) | |
| # Unit tests nastily inline to maintain single-file distribution | |
| import pytest | |
| TEST_DATA = [ | |
| ("00E24DAF66A0703A3800", "2026-02-27 09:15:29.563395"), | |
| ("00E24DAF66A070809400", "2026-02-27 09:15:29.563400"), | |
| ("00E24DB65ACB5167B800", "2026-02-27 09:46:36.204310"), | |
| ("00E24DE230235168D000", "2026-02-27 13:02:42.636054"), | |
| ("00E251990A023F8F6600", "2026-03-02 11:56:44.773368"), | |
| ("00E251997CD44256AA00", "2026-03-02 11:58:45.171237"), | |
| ("00E26F8A83368F9DB800", "2026-03-26 07:31:29.635577"), | |
| ("00E26F8A83511BF25000", "2026-03-26 07:31:29.744319"), | |
| ] | |
| @pytest.mark.parametrize("lrsn, db2_timestamp", TEST_DATA) | |
| def test_decode_lrsn(lrsn, db2_timestamp): | |
| """Compare a timestamp from decode_lrsn with a timestamp from Db2 utilities""" | |
| td = abs(decode_lrsn(lrsn)["datetime_utc"] - datetime.fromisoformat(db2_timestamp).replace(tzinfo=timezone.utc)) | |
| assert td <= timedelta(microseconds=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment