Return None from tzlocal.tzname(None) when the zone has DST (#1674)
datetime.time objects have no date, so they pass None to the tzinfo
methods. When the local zone observes DST, tzlocal.utcoffset() and
tzlocal.dst() already return None for that, but tzname() passed None on
to _isdst(), so time(13, 20, tzinfo=tz.tzlocal()).tzname() and
.strftime("%Z") raised "AttributeError: 'NoneType' object has no
attribute 'replace'".
Return None from tzname() under the same condition as the other two
methods. This matches tzfile, which returns None from all three for
zones with transitions. Zones without DST still return their standard
abbreviation.
diff --git a/AUTHORS.md b/AUTHORS.md
index 0d49dc2..0f1ece8 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -114,6 +114,7 @@
- Sherry Zhou (gh: @cssherry) **D**
- Siping Meng (gh: @smeng10) **D**
- Stefan Bonchev **D**
+- Terry Cheng (gh: @terry9046) **D**
- Thierry Bastian <thierryb@MASKED>
- Thomas A Caswell <tcaswell@MASKED> (gh: @tacaswell) **R**
- Thomas Achtemichuk <tom@MASKED>
diff --git a/changelog.d/1674.bugfix.rst b/changelog.d/1674.bugfix.rst
new file mode 100644
index 0000000..f3af9fa
--- /dev/null
+++ b/changelog.d/1674.bugfix.rst
@@ -0,0 +1 @@
+``tzlocal().tzname()`` now returns ``None`` when called without a datetime (e.g. from a ``datetime.time``) in a local zone with DST, as ``utcoffset()`` and ``dst()`` already did, instead of raising ``AttributeError``. Reported and fixed by @terry9046 (gh pr #1674)
diff --git a/src/dateutil/tz/tz.py b/src/dateutil/tz/tz.py
index b1bcebe..1f19132 100644
--- a/src/dateutil/tz/tz.py
+++ b/src/dateutil/tz/tz.py
@@ -219,6 +219,9 @@
return ZERO
def tzname(self, dt):
+ if dt is None and self._hasdst:
+ return None
+
return self._tznames[self._isdst(dt)]
def is_ambiguous(self, dt):
diff --git a/tests/test_tz.py b/tests/test_tz.py
index 107019c..02d7169 100644
--- a/tests/test_tz.py
+++ b/tests/test_tz.py
@@ -1026,6 +1026,20 @@
assert not (tz.tzlocal() == tzoff)
+@mark_tzlocal_nix
[email protected](
+ "tzvar, tzname",
+ [
+ ("UTC", "UTC"),
+ ("EST5", "EST"),
+ ("EST+5EDT,M3.2.0/2,M11.1.0/2", None),
+ ],
+)
+def test_tzlocal_time_only_tzname(tzvar, tzname):
+ with TZEnvContext(tzvar):
+ assert dt_time(13, 20, tzinfo=tz.tzlocal()).tzname() == tzname
+
+
@pytest.mark.gettz
class GettzTest(TzSourceMixin, unittest.TestCase, TzFoldMixin):
gettz = staticmethod(tz.gettz)