summaryrefslogtreecommitdiff
path: root/django/utils/timezone.py
diff options
context:
space:
mode:
authorAymeric Augustin <aymeric.augustin@m4x.org>2014-05-16 23:12:59 +0200
committerAymeric Augustin <aymeric.augustin@m4x.org>2014-05-16 23:12:59 +0200
commit1109ebd7b373e14b68616346ea5dd3e89a8ae2fe (patch)
treeace55cb69900fe2953ec562a8a072939c15f6dbf /django/utils/timezone.py
parentfa89acf1d0a4adbf0802c1275494f5159a912c9e (diff)
Optimized make_aware/naive by removing redundant checks. Refs #22625.
Also added tests with pytz and removed misplaced tests.
Diffstat (limited to 'django/utils/timezone.py')
-rw-r--r--django/utils/timezone.py20
1 files changed, 12 insertions, 8 deletions
diff --git a/django/utils/timezone.py b/django/utils/timezone.py
index 8138767fb2..0c44d4fd4d 100644
--- a/django/utils/timezone.py
+++ b/django/utils/timezone.py
@@ -306,9 +306,11 @@ def localtime(value, timezone=None):
"""
if timezone is None:
timezone = get_current_timezone()
+ # If `value` is naive, astimezone() will raise a ValueError,
+ # so we don't need to perform a redundant check.
value = value.astimezone(timezone)
if hasattr(timezone, 'normalize'):
- # available for pytz time zones
+ # This method is available for pytz time zones.
value = timezone.normalize(value)
return value
@@ -351,13 +353,15 @@ def make_aware(value, timezone):
"""
Makes a naive datetime.datetime in a given time zone aware.
"""
- if is_aware(value):
- raise ValueError("make_aware expects a naive value, got %s" % value)
if hasattr(timezone, 'localize'):
- # available for pytz time zones
+ # This method is available for pytz time zones.
return timezone.localize(value, is_dst=None)
else:
- # may be wrong around DST changes
+ # Check that we won't overwrite the timezone of an aware datetime.
+ if is_aware(value):
+ raise ValueError(
+ "make_aware expects a naive datetime, got %s" % value)
+ # This may be wrong around DST changes!
return value.replace(tzinfo=timezone)
@@ -365,10 +369,10 @@ def make_naive(value, timezone):
"""
Makes an aware datetime.datetime naive in a given time zone.
"""
- if is_naive(value):
- raise ValueError("make_naive expects an aware value, got %s" % value)
+ # If `value` is naive, astimezone() will raise a ValueError,
+ # so we don't need to perform a redundant check.
value = value.astimezone(timezone)
if hasattr(timezone, 'normalize'):
- # available for pytz time zones
+ # This method is available for pytz time zones.
value = timezone.normalize(value)
return value.replace(tzinfo=None)