Simplified django.utils.dateformat methods.

This removes unnecessary format('O') call, remove unnecessary method
calls for simple cases in TimeFormat, and simplifies time zone handling
in TimeFormat.
This commit is contained in:
Nick Pope 2021-05-13 13:33:19 +01:00 committed by Mariusz Felisiak
parent 6afc2a944c
commit 1f4908b01a
1 changed files with 17 additions and 22 deletions

View File

@ -59,6 +59,13 @@ class TimeFormat(Formatter):
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)
)
def a(self):
"'a.m.' or 'p.m.'"
if self.data.hour > 11:
@ -94,9 +101,9 @@ class TimeFormat(Formatter):
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
"""
if self.data.minute == 0:
return self.g()
return '%s:%s' % (self.g(), self.i())
hour = self.data.hour % 12 or 12
minute = self.data.minute
return '%d:%02d' % (hour, minute) if minute else hour
def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
@ -108,11 +115,11 @@ class TimeFormat(Formatter):
def h(self):
"Hour, 12-hour format; i.e. '01' to '12'"
return '%02d' % self.g()
return '%02d' % (self.data.hour % 12 or 12)
def H(self):
"Hour, 24-hour format; i.e. '00' to '23'"
return '%02d' % self.G()
return '%02d' % self.data.hour
def i(self):
"Minutes; i.e. '00' to '59'"
@ -124,12 +131,10 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
if not self.timezone:
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ""
seconds = self.Z()
if seconds == "":
return ""
sign = '-' if seconds < 0 else '+'
seconds = abs(seconds)
return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
@ -157,14 +162,10 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
if not self.timezone:
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ""
if not _datetime_ambiguous_or_imaginary(self.data, self.timezone):
name = self.timezone.tzname(self.data)
else:
name = self.format('O')
return str(name)
return str(self.timezone.tzname(self.data))
def u(self):
"Microseconds; i.e. '000000' to '999999'"
@ -178,10 +179,7 @@ class TimeFormat(Formatter):
If timezone information is not available, return an empty string.
"""
if (
not self.timezone or
_datetime_ambiguous_or_imaginary(self.data, self.timezone)
):
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ""
offset = self.timezone.utcoffset(self.data)
@ -223,10 +221,7 @@ class DateFormat(TimeFormat):
def I(self): # NOQA: E743, E741
"'1' if Daylight Savings Time, '0' otherwise."
if (
not self.timezone or
_datetime_ambiguous_or_imaginary(self.data, self.timezone)
):
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ''
return '1' if self.timezone.dst(self.data) else '0'