Skip to content

Commit e169f88

Browse files
committed
date_utils: make date specificity sorting safer
1 parent 29b14ed commit e169f88

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

library/utils/date_utils.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,26 @@ def super_parser(date_str, fallback=False):
3737
return None
3838

3939

40+
def date_specificity_sort_key(d):
41+
month_flag = bool(getattr(d, "month", None))
42+
day_flag = bool(getattr(d, "day", None))
43+
44+
try:
45+
ts = d.timestamp()
46+
ts_key = -ts
47+
except Exception: # fallback for invalid year/timestamp
48+
ts_key = float("-inf")
49+
50+
return (month_flag, day_flag, ts_key)
51+
52+
4053
def specific_date(*dates):
4154
valid_dates = [super_parser(s) for s in dates if s]
4255
past_dates = [d for d in valid_dates if d and d < maybe_tz_now(d)]
4356
if not past_dates:
4457
return None
4558

46-
earliest_specific_date = sorted(
47-
past_dates, key=lambda d: (bool(d.month), bool(d.day), -d.timestamp()), reverse=True
48-
)[0]
59+
earliest_specific_date = sorted(past_dates, key=date_specificity_sort_key, reverse=True)[0]
4960
return nums.to_timestamp(earliest_specific_date)
5061

5162

0 commit comments

Comments
 (0)