Skip to content

Commit

Permalink
Handle dates that fall within an hour of daylight saving time ending
Browse files Browse the repository at this point in the history
  • Loading branch information
Rebecca Drabenstott authored and rebecca-draben committed May 29, 2024
1 parent a57c129 commit 3af3c9e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
22 changes: 19 additions & 3 deletions dear_petition/petition/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import pytest
from pytest_django.fixtures import settings
import pytz
from django.conf import settings
from django.utils.timezone import make_aware, utc
from datetime import datetime, date

Expand Down Expand Up @@ -75,6 +72,25 @@ def test_make_datetime_aware(settings):
assert aware_dt == None


def test_make_datetime_aware_ambiguous(settings):
"""Aware Datetime should be returned assuming standard time in the case of ambiguity between standard time and
daylight saving time.
"""
# Set the TIME_ZONE in the settings.
settings.TIME_ZONE = "America/New_York"

# Calling pu.make_datetime_aware() with a date/time that falls within the hour before or after daylight saving time
# ends returns a timezone-aware datetime referring to the moment from the naive_datetime_obj, in the appropriate
# time zone, assuming standard time.
naive_datetime_str = "2011-11-06T01:46:00"
expected_datetime_obj = make_aware(
datetime(year=2011, month=11, day=6, hour=1, minute=46, second=0),
timezone=pytz.timezone("America/New_York"),
is_dst=False
)
assert pu.make_datetime_aware(naive_datetime_str) == expected_datetime_obj


def test_format_petition_date(settings):
"""Should return %m/%d/%Y date. If it is non-EST datetime, it will convert to EST first."""

Expand Down
13 changes: 10 additions & 3 deletions dear_petition/petition/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,16 @@ def make_datetime_aware(dt_str):
naive_datetime_obj = dateutil.parser.parse(dt_str)

# b) Assign the timezone-naive datetime a timezone based on settings.TIME_ZONE
aware_datetime_obj = make_aware(
naive_datetime_obj, pytz.timezone(settings.TIME_ZONE)
)
tz = pytz.timezone(settings.TIME_ZONE)
try:
aware_datetime_obj = make_aware(naive_datetime_obj, tz)
except pytz.exceptions.AmbiguousTimeError:
# Ambiguity occurs when the date/time falls within the hour before or after daylight saving time ends. For
# example, if the date/time is November 6, 2011 01:46 AM, it is not known if the time is before or after the
# time change since that time occurs twice on that date. However, this level of granularity is not important in
# expungement, so default to standard time in case of ambiguity.
aware_datetime_obj = make_aware(naive_datetime_obj, tz, is_dst=False)

# Return the timezone aware object.
return aware_datetime_obj

Expand Down

0 comments on commit 3af3c9e

Please sign in to comment.