Simplified handling ambiguous/imaginary datetimes in django.utils.dateformat.
Instead of the separate property, we can just not set self.timezone if
the datetime is ambiguous or imaginary. This ensures that this check
will only ever happen once as it's dependant on the datetime object and
not the format string characters.
@@ -56,20 +56,16 @@ class TimeFormat(Formatter):
self.data = obj
self.timezone = None
- # We only support timezone when formatting datetime objects,
- # not date objects (timezone information not appropriate),
- # or time objects (against established django policy).
if isinstance(obj, datetime):
+ # Timezone is only supported when formatting datetime objects, not
+ # date objects (timezone information not appropriate), or time
+ # objects (against established django policy).
if is_naive(obj):
- self.timezone = get_default_timezone()
+ timezone = get_default_timezone()
else:
- self.timezone = obj.tzinfo
-
- @property
- def _no_timezone_or_datetime_is_ambiguous_or_imaginary(self):
- return not self.timezone or _datetime_ambiguous_or_imaginary(
- self.data, self.timezone
- )
+ timezone = obj.tzinfo
+ if not _datetime_ambiguous_or_imaginary(obj, timezone):
+ self.timezone = timezone
def a(self):
"'a.m.' or 'p.m.'"
@@ -136,7 +132,7 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
- if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
+ if self.timezone is None:
return ""
offset = self.timezone.utcoffset(self.data)
@@ -168,7 +164,7 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
- if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
+ if self.timezone is None:
return ""
return str(self.timezone.tzname(self.data))
@@ -185,7 +181,7 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
- if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
+ if self.timezone is None:
return ""
offset = self.timezone.utcoffset(self.data)
@@ -227,7 +223,7 @@ class DateFormat(TimeFormat):
def I(self): # NOQA: E743, E741
"'1' if daylight saving time, '0' otherwise."
- if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
+ if self.timezone is None:
return ""
return "1" if self.timezone.dst(self.data) else "0"
