Skip to content

Commit 079d11c

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

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

library/utils/date_utils.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import dateutil.parser
55

6-
from library.utils import iterables, nums
6+
from library.utils import consts, iterables, nums
77

88

99
def is_tz_aware(dt: datetime.datetime) -> bool:
@@ -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 = consts.APPLICATION_START
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

library/utils/nums.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import math, re, statistics
22

3+
from library.utils import consts
4+
35

46
def percent(value, total):
57
if total == 0:
@@ -26,7 +28,10 @@ def percentage_difference(value1, value2):
2628

2729

2830
def to_timestamp(dt_object):
29-
return int(dt_object.timestamp())
31+
try:
32+
return int(dt_object.timestamp())
33+
except ValueError:
34+
return consts.APPLICATION_START
3035

3136

3237
def safe_int(s) -> int | None:

0 commit comments

Comments
 (0)