From 82e164ce851cc42b8af7fe99d9996f10bb87a448 Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Wed, 5 Jun 2024 21:06:28 -0500 Subject: [PATCH] LeapSecondInfo: use dataclass instead of NamedTuple The documentation workaround for the dataclass was worse than the benefit from being able to tuple-unpack it. --- leapseconddata/__init__.py | 23 +++++++++++------------ leapseconddata/__main__.py | 4 ++-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/leapseconddata/__init__.py b/leapseconddata/__init__.py index 9379422..04dca8c 100755 --- a/leapseconddata/__init__.py +++ b/leapseconddata/__init__.py @@ -29,22 +29,20 @@ import re import urllib.request from dataclasses import dataclass, field -from typing import BinaryIO, List, NamedTuple, Optional, Union +from typing import BinaryIO, List, Optional, Union tai = datetime.timezone(datetime.timedelta(0), "TAI") NTP_EPOCH = datetime.datetime(1900, 1, 1, tzinfo=datetime.timezone.utc) -LeapSecondInfo = NamedTuple( - "LeapSecondInfo", (("start", datetime.datetime), ("tai", datetime.timedelta)) -) -LeapSecondInfo.start.__doc__ = """The UTC timestamp just after the insertion of the leap second. +@dataclass(frozen=True) +class LeapSecondInfo: + start: datetime.datetime + """The UTC timestamp just after the insertion of the leap second.""" -The leap second is actually the 60th second of the previous minute""" -LeapSecondInfo.tai.__doc__ = ( + tai_offset: datetime.timedelta """The new TAI-UTC offset. Positive numbers indicate that TAI is ahead of UTC""" -) class ValidityError(ValueError): @@ -130,13 +128,14 @@ def tai_offset( return datetime.timedelta(0) old_tai = datetime.timedelta() - for start, tai_offset in self.leap_seconds: + for leap_second in self.leap_seconds: + start = leap_second.start if is_tai: - start += tai_offset - datetime.timedelta(seconds=1) + start += leap_second.tai_offset - datetime.timedelta(seconds=1) if when < start: return old_tai - old_tai = tai_offset - return self.leap_seconds[-1].tai + old_tai = leap_second.tai_offset + return self.leap_seconds[-1].tai_offset def to_tai( self, when: datetime.datetime, check_validity: bool = True diff --git a/leapseconddata/__main__.py b/leapseconddata/__main__.py index 0cf17ce..e333d2a 100644 --- a/leapseconddata/__main__.py +++ b/leapseconddata/__main__.py @@ -20,8 +20,8 @@ def main() -> None: lsd = LeapSecondData.from_standard_source() print(f"Last updated: {lsd.last_updated:%Y-%m-%d}") print(f"Valid until: {lsd.valid_until:%Y-%m-%d}") - for when, offset in lsd.leap_seconds[-10:]: - print(f"{when:%Y-%m-%d}: {offset.total_seconds()}") + for leap_second in lsd.leap_seconds[-10:]: + print(f"{leap_second.start:%Y-%m-%d}: {leap_second.tai_offset.total_seconds()}") when = datetime.datetime(2011, 1, 1, tzinfo=datetime.timezone.utc) print(f"TAI-UTC on {when:%Y-%m-%d} was {lsd.tai_offset(when).total_seconds()}")