From 3f186b3ddbb13b2750e83d3d9d384b3971209c68 Mon Sep 17 00:00:00 2001 From: rlskoeser Date: Wed, 9 Nov 2022 17:06:51 -0500 Subject: [PATCH] Ensure years are always 4 digits #20 --- tests/test_dateformat/test_iso8601.py | 6 ++++++ tests/test_undate.py | 2 +- undate/dateformat/iso8601.py | 12 +++++++++--- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/test_dateformat/test_iso8601.py b/tests/test_dateformat/test_iso8601.py index b03058a..ee69c47 100644 --- a/tests/test_dateformat/test_iso8601.py +++ b/tests/test_dateformat/test_iso8601.py @@ -25,3 +25,9 @@ def test_parse_range(self): assert ISO8601DateFormat().parse("1800/1900") == UndateInterval( Undate(1800), Undate(1900) ) + + def test_to_string(self): + # NOTE: iso8601 to_string currently tested more thoroughly + # in undate str tests; may want to move those tests here + assert ISO8601DateFormat().to_string(Undate(900)) == "0900" + assert ISO8601DateFormat().to_string(Undate(33)) == "0033" diff --git a/tests/test_undate.py b/tests/test_undate.py index 3e70e69..5e58cd9 100644 --- a/tests/test_undate.py +++ b/tests/test_undate.py @@ -44,7 +44,7 @@ def test_str(self): def test_str_open_range(self): # 900 - - assert str(UndateInterval(Undate(900))) == "900/" + assert str(UndateInterval(Undate(900))) == "0900/" # - 1900 assert str(UndateInterval(latest=Undate(1900))) == "../1900" # - 1900-12 diff --git a/undate/dateformat/iso8601.py b/undate/dateformat/iso8601.py index eecb431..5bf9896 100644 --- a/undate/dateformat/iso8601.py +++ b/undate/dateformat/iso8601.py @@ -51,9 +51,15 @@ def to_string(self, undate: Undate) -> str: # then combine for date_portion, known in undate.known_values.items(): if known: - date_parts.append( - undate.earliest.strftime(self.iso_format[date_portion]) - ) + # NOTE: datetime strftime for %Y for 3-digit year + # results in leading zero in some environments + # and not others; force year to always be 4 digits + if date_portion == "year": + date_parts.append("%04d" % undate.earliest.year) + else: + date_parts.append( + undate.earliest.strftime(self.iso_format[date_portion]) + ) elif date_portion == "year": # if not known but this is year, add '-' for --MM-DD unknown year format date_parts.append("-")