diff --git a/dear_petition/petition/tests/test_utils.py b/dear_petition/petition/tests/test_utils.py index 3b35f26f..f9cac2f9 100644 --- a/dear_petition/petition/tests/test_utils.py +++ b/dear_petition/petition/tests/test_utils.py @@ -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 @@ -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.""" diff --git a/dear_petition/petition/utils.py b/dear_petition/petition/utils.py index 79d0c18f..41d7fd0d 100644 --- a/dear_petition/petition/utils.py +++ b/dear_petition/petition/utils.py @@ -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