Date Utils
Utility functions for time-related operations in retail analysis.
filter_and_label_by_periods(transactions, period_ranges, period_col='period_name')
Filter transactions to named time periods and label each row with its period.
Rows outside every period are dropped. The date column is read from the
column.transaction_date option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transactions
|
DataFrame | Table
|
Transactions containing the transaction date column. |
required |
period_ranges
|
Mapping[str, tuple[datetime | date | str, datetime | date | str]]
|
Period
names mapped to inclusive |
required |
period_col
|
str
|
Name of the label column to add. Defaults to |
'period_name'
|
Returns:
| Type | Description |
|---|---|
Table
|
ibis.Table: Filtered table with the |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Examples:
>>> from openretailscience.utils import filter_and_label_by_periods
>>> periods = {"H1 2024": ("2024-01-01", "2024-06-30"), "H1 2025": ("2025-01-01", "2025-06-30")}
>>> h1 = filter_and_label_by_periods(transactions, period_ranges=periods)
>>> h1.group_by("period_name").aggregate(spend=h1.unit_spend.sum()).order_by("period_name").to_pandas()
period_name spend
0 H1 2024 1194.05
1 H1 2025 1350.15
Source code in openretailscience/utils/date.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
find_overlapping_periods(start_date, end_date, return_str=True)
Split a date range into year-aligned overlapping periods.
The first period starts at start_date; each subsequent period starts on the same
month and day one year later. Each period ends on end_date's month and day in the
following year, so the last period ends exactly at end_date. Both dates in the
same year yield an empty list.
Note
No leap-year adjustment: a Feb 29 start or end date raises ValueError in a
non-leap year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
datetime | str
|
Range start, a datetime or |
required |
end_date
|
datetime | str
|
Range end, a datetime or |
required |
return_str
|
bool
|
If True, dates are returned as ISO-formatted strings; if False, as datetime objects. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
list[tuple[str | datetime, str | datetime]]
|
list[tuple[str | datetime, str | datetime]]: |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the start date is after the end date. |
Examples:
>>> from openretailscience.utils import find_overlapping_periods
>>> find_overlapping_periods("2023-10-01", "2025-12-31")
[('2023-10-01', '2024-12-31'), ('2024-10-01', '2025-12-31')]