Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(api): correct DST spring-forward handling in parse_time_range (#39231)

Loi Nguyen2f11967e8e4f
diff --git a/api/libs/datetime_utils.py b/api/libs/datetime_utils.py
index e25fb2d913c..5ac970c0671 100644
--- a/api/libs/datetime_utils.py
+++ b/api/libs/datetime_utils.py
@@ -74,7 +74,9 @@ def parse_time_range(
) -> tuple[datetime.datetime | None, datetime.datetime | None]:
"""
Parse time range strings and convert to UTC datetime objects.
- Handles DST ambiguity and non-existent times gracefully.
+ Ambiguous times use ``is_dst=False``. Non-existent local times shift
+ forward by the actual timezone offset change, preserving their position
+ within the gap.
Args:
start: Start time string (YYYY-MM-DD HH:MM)
@@ -82,10 +84,12 @@ def parse_time_range(
tzname: Timezone name
Returns:
- tuple: (start_datetime_utc, end_datetime_utc)
+ tuple: (start_datetime_utc, end_datetime_utc), with None for empty bounds.
+ Non-empty bounds are timezone-aware UTC datetimes with start <= end.
Raises:
- ValueError: When time range is invalid or start > end
+ ValueError: When a time format is invalid or the parsed start > end.
+ pytz.UnknownTimeZoneError: When tzname is not a recognized timezone.
"""
tz = pytz.timezone(tzname)
utc = pytz.utc
@@ -104,8 +108,9 @@ def parse_time_range(
except pytz.AmbiguousTimeError:
return tz.localize(dt, is_dst=False).astimezone(utc)
except pytz.NonExistentTimeError:
- dt += datetime.timedelta(hours=1)
- return tz.localize(dt, is_dst=None).astimezone(utc)
+ # Use the pre-transition offset, then normalize to shift forward
+ # by the actual gap size while preserving the position within it.
+ return tz.normalize(tz.localize(dt, is_dst=False)).astimezone(utc)
start_dt = _parse(start, "start")
end_dt = _parse(end, "end")
diff --git a/api/tests/unit_tests/libs/test_datetime_utils.py b/api/tests/unit_tests/libs/test_datetime_utils.py
index 760bb5a93ac..9a49d524454 100644
--- a/api/tests/unit_tests/libs/test_datetime_utils.py
+++ b/api/tests/unit_tests/libs/test_datetime_utils.py
@@ -178,36 +178,57 @@ class TestParseTimeRange:
assert start is not None
assert end is not None
- def test_parse_time_range_dst_nonexistent_time(self) -> None:
- """Test parsing during DST nonexistent time (spring forward)."""
- with patch("pytz.timezone", autospec=True) as mock_timezone:
- # Mock timezone that raises NonExistentTimeError
- mock_tz = mock_timezone.return_value
-
- # Create a mock datetime object for the return value
- mock_dt = datetime.datetime(2024, 1, 1, 10, 0, 0)
- mock_utc_dt = mock_dt.replace(tzinfo=pytz.UTC)
-
- # Create a proper mock for the localized datetime
- from unittest.mock import MagicMock
-
- mock_localized_dt = MagicMock()
- mock_localized_dt.astimezone.return_value = mock_utc_dt
+ @pytest.mark.parametrize(
+ ("tzname", "time_str", "expected"),
+ [
+ pytest.param(
+ "America/New_York",
+ "2024-03-10 02:30",
+ datetime.datetime(2024, 3, 10, 7, 30, tzinfo=pytz.UTC),
+ id="one-hour-gap",
+ ),
+ pytest.param(
+ "Australia/Lord_Howe",
+ "2024-10-06 02:15",
+ datetime.datetime(2024, 10, 5, 15, 45, tzinfo=pytz.UTC),
+ id="half-hour-gap",
+ ),
+ pytest.param(
+ "Antarctica/Troll",
+ "2024-03-31 01:30",
+ datetime.datetime(2024, 3, 31, 1, 30, tzinfo=pytz.UTC),
+ id="two-hour-gap",
+ ),
+ pytest.param(
+ "Pacific/Apia",
+ "2011-12-30 12:00",
+ datetime.datetime(2011, 12, 30, 22, tzinfo=pytz.UTC),
+ id="skipped-day",
+ ),
+ pytest.param(
+ "Europe/Dublin",
+ "2024-03-31 01:30",
+ datetime.datetime(2024, 3, 31, 1, 30, tzinfo=pytz.UTC),
+ id="negative-dst",
+ ),
+ pytest.param(
+ "Asia/Kathmandu",
+ "1986-01-01 00:05",
+ datetime.datetime(1985, 12, 31, 18, 35, tzinfo=pytz.UTC),
+ id="non-dst-quarter-hour-gap",
+ ),
+ ],
+ )
+ def test_parse_time_range_nonexistent_local_time(
+ self, tzname: str, time_str: str, expected: datetime.datetime
+ ) -> None:
+ """Both bounds shift forward by the real gap size and resolve to exact UTC instants."""
+ start, end = parse_time_range(time_str, time_str, tzname)
- # Set up side effects: first call raises exception, second call succeeds
- mock_tz.localize.side_effect = [
- pytz.NonExistentTimeError("Non-existent time"), # First call for start
- mock_localized_dt, # Second call for start (with adjusted time)
- pytz.NonExistentTimeError("Non-existent time"), # First call for end
- mock_localized_dt, # Second call for end (with adjusted time)
- ]
-
- start, end = parse_time_range("2024-01-01 10:00", "2024-01-01 18:00", "US/Eastern")
-
- # Should adjust time forward by 1 hour for nonexistent times
- assert mock_tz.localize.call_count == 4 # 2 calls per time (first fails, second succeeds)
- assert start is not None
- assert end is not None
+ assert start is not None
+ assert end is not None
+ assert start == end == expected
+ assert start.tzinfo == end.tzinfo == pytz.UTC
def test_parse_time_range_edge_cases(self) -> None:
"""Test edge cases for time parsing."""