Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#28323 closed Cleanup/optimization (fixed)

Redundant use of normalize() in django.utils.timezone.localtime() and make_naive()

Reported by: Sergei Zh Owned by: nobody
Component: Utilities Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I'm not 100% sure , but I didn't find any test on this and can't think of any.
What the purpose of using timezone.normalize method after dt.astimezone if pytz installed?

Current implementation of datetime.astimezone (according to python 2/3 docs):

def astimezone(self, tz):
    if self.tzinfo is tz:
        return self
    # Convert self to UTC, and attach the new time zone object.
    utc = (self - self.utcoffset()).replace(tzinfo=tz)
    # Convert from UTC to tz's local time.
    return tz.fromutc(utc)

The implementation of normalize method for StaticTzInfo is astimezone:

if dt.tzinfo is self:
    return dt
if dt.tzinfo is None:
    raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)

And for DstTzInfo normalize implementation is the same as datetime.astimezone:

if dt.tzinfo is None:
    raise ValueError('Naive time - no tzinfo set')

# Convert dt in localtime to UTC
offset = dt.tzinfo._utcoffset
dt = dt.replace(tzinfo=None)
dt = dt - offset
# convert it back, and return it
return self.fromutc(dt)

I've checked pytz 2011k and 2017.2 versions, looks like this code has never changed.

Also I found this conversation https://answers.launchpad.net/pytz/+question/249229

Change History (4)

comment:1 by Tim Graham, 7 years ago

Has patch: set
Summary: Redundant use of `normalize` in `django.utils.localtime`Redundant use of normalize() in django.utils.timezone.localtime()
Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization

PR -- the tests seems to pass, so unless we're missing a test case to show why normalize() is needed, I'd think your analysis is correct.

comment:2 by Tim Graham, 7 years ago

Summary: Redundant use of normalize() in django.utils.timezone.localtime()Redundant use of normalize() in django.utils.timezone.localtime() and make_naive()

comment:3 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: newclosed

In bdf20c38:

Fixed #28323 -- Removed unneeded normalize() in timezone.localtime() and make_naive().

comment:4 by Aymeric Augustin, 7 years ago

I was merely following the pytz docs, before they were updated in version 2016.4.

Note: See TracTickets for help on using tickets.
Back to Top