calbridgepy 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of calbridgepy might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bistoon Hosseini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: calbridgepy
3
+ Version: 0.1.1
4
+ Summary: Fast date conversion and difference functions for Jalali, Gregorian, and Hijri calendars
5
+ Author-email: Bistoon Hosseini <bistoon.hosseini@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pandas>=1.5
11
+ Provides-Extra: polars
12
+ Requires-Dist: polars>=0.20; extra == "polars"
13
+ Dynamic: license-file
14
+
15
+ # calbridge
16
+
17
+ **calbridge** is a high-performance Python package for **fast and accurate conversion** between Jalali (Shamsi), Gregorian, and Hijri calendars.
18
+ It efficiently handles **large datasets** using a **pre-built mapping table** covering **Gregorian years 1700–2200**, with exact aligned mappings for **Jalali** and **Hijri** dates.
19
+
20
+ The package provides five main functions:
21
+
22
+ 1. `normalize_date()`: Normalize date strings to `"YYYY-MM-DD"` format, preserving optional time components.
23
+ 2. `convert_date()`: Convert dates between any two calendars (Jalali, Gregorian, Hijri) using vectorized joins/lookups.
24
+ 3. `day2day()`: Generate a sequence of dates between two endpoints in the chosen calendar, including optional start and end times.
25
+ 4. `date_diff()`: Compute the difference in days between two dates in any supported calendar using fast index lookups.
26
+ 5. `date_time_diff()`: Compute the difference between two date-time values in any calendar. Returns both raw seconds and a formatted `"X days HH:MM:SS"` string.
27
+
28
+ ### Performance & Backend Flexibility
29
+ The package is designed with **zero heavy runtime overhead**:
30
+ - Uses **polars** when available for lightning-fast vectorized joins and parallel processing.
31
+ - Automatically falls back to **pandas** if Polars is not installed.
32
+ - Requires no heavy binary serialization dependencies (such as `pyarrow`).
33
+
34
+ ---
35
+
36
+ ## Installation
37
+
38
+ Install directly from GitHub via `pip`:
39
+
40
+ ```bash
41
+ pip install https://github.com/bistoonh/calbridge/archive/refs/heads/main.zip
42
+ ```
43
+
44
+ To install with optional **Polars** acceleration support:
45
+
46
+ ```bash
47
+ pip install "calbridge[polars] @ https://github.com/bistoonh/calbridge/archive/refs/heads/main.zip"
48
+ ```
49
+
50
+ ---
51
+
52
+ ## Examples
53
+
54
+ ```python
55
+ from calbridge import (
56
+ normalize_date,
57
+ convert_date,
58
+ day2day,
59
+ date_diff,
60
+ date_time_diff,
61
+ )
62
+
63
+ # 1. Normalize dates (Jalali)
64
+ normalize_date(["14020101", "1402-01", "1402-01-01 14:30:00"])
65
+ # ['1402-01-01', '1402-01-01', '1402-01-01 14:30:00']
66
+
67
+ # Single string input returns a string
68
+ normalize_date("14020101")
69
+ # '1402-01-01'
70
+
71
+
72
+ # 2. Convert Jalali to Gregorian
73
+ convert_date("1402-01-01", from_cal="j", to_cal="g")
74
+ # '2023-03-21'
75
+
76
+ # Convert Gregorian to Hijri
77
+ convert_date("2023-03-21", from_cal="g", to_cal="h")
78
+ # '1444-08-29'
79
+
80
+ # Vectorized conversions
81
+ dates = ["1402-01-01", "1402-05-15", "1402-12-29"]
82
+ convert_date(dates, from_cal="j", to_cal="g")
83
+ # ['2023-03-21', '2023-08-06', '2024-03-18']
84
+
85
+
86
+ # 3. Generate a sequence of Hijri dates
87
+ day2day("1447-09-01", "1447-09-03", calendar="h")
88
+ # ['1447-09-01', '1447-09-02', '1447-09-03']
89
+
90
+ # Include start and end times (only attached at endpoints)
91
+ day2day("2025-03-21 08:00:00", "2025-03-23 18:00:00", calendar="g")
92
+ # ['2025-03-21 08:00:00', '2025-03-22', '2025-03-23 18:00:00']
93
+
94
+
95
+ # 4. Compute day differences (Gregorian)
96
+ date_diff("2025-03-21", "2025-03-25", calendar="g")
97
+ # 4
98
+
99
+ # Vectorized day differences (Hijri)
100
+ date_diff(
101
+ ["1447-09-01", "1447-09-05"],
102
+ ["1447-09-03", "1447-09-10"],
103
+ calendar="h",
104
+ )
105
+ # [2, 5]
106
+
107
+
108
+ # 5. Compute date-time differences (seconds + formatted)
109
+ res = date_time_diff("1402-01-01 12:00:00", "1402-01-02 14:30:00", calendar="j")
110
+ print(res["seconds"])
111
+ # 95400
112
+
113
+ print(res["formatted"])
114
+ # '1 days 02:30:00'
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Data
120
+
121
+ The package includes a **pre-indexed calendar mapping** covering 1700 to 2200 CE:
122
+
123
+ ```python
124
+ from calbridge.normalize_date import _get_calendar_map
125
+
126
+ df = _get_calendar_map()
127
+ # Returns a Polars DataFrame (if installed) or Pandas DataFrame
128
+ ```
129
+
130
+ This table maps Jalali, Gregorian, and Hijri dates across multiple centuries, allowing instant O(1) lookups and fast vectorized joins without recalculating leap years or month structures on every call.
131
+
132
+ ---
133
+
134
+ ## Calendar Identifier Aliases
135
+
136
+ All functions accept both full names and short aliases:
137
+ - **Jalali / Shamsi:** `"j"`, `"jalali"`
138
+ - **Gregorian:** `"g"`, `"gregorian"`
139
+ - **Hijri:** `"h"`, `"hijri"`
140
+
141
+ ---
142
+
143
+ ## License
144
+
145
+ MIT License
@@ -0,0 +1,131 @@
1
+ # calbridge
2
+
3
+ **calbridge** is a high-performance Python package for **fast and accurate conversion** between Jalali (Shamsi), Gregorian, and Hijri calendars.
4
+ It efficiently handles **large datasets** using a **pre-built mapping table** covering **Gregorian years 1700–2200**, with exact aligned mappings for **Jalali** and **Hijri** dates.
5
+
6
+ The package provides five main functions:
7
+
8
+ 1. `normalize_date()`: Normalize date strings to `"YYYY-MM-DD"` format, preserving optional time components.
9
+ 2. `convert_date()`: Convert dates between any two calendars (Jalali, Gregorian, Hijri) using vectorized joins/lookups.
10
+ 3. `day2day()`: Generate a sequence of dates between two endpoints in the chosen calendar, including optional start and end times.
11
+ 4. `date_diff()`: Compute the difference in days between two dates in any supported calendar using fast index lookups.
12
+ 5. `date_time_diff()`: Compute the difference between two date-time values in any calendar. Returns both raw seconds and a formatted `"X days HH:MM:SS"` string.
13
+
14
+ ### Performance & Backend Flexibility
15
+ The package is designed with **zero heavy runtime overhead**:
16
+ - Uses **polars** when available for lightning-fast vectorized joins and parallel processing.
17
+ - Automatically falls back to **pandas** if Polars is not installed.
18
+ - Requires no heavy binary serialization dependencies (such as `pyarrow`).
19
+
20
+ ---
21
+
22
+ ## Installation
23
+
24
+ Install directly from GitHub via `pip`:
25
+
26
+ ```bash
27
+ pip install https://github.com/bistoonh/calbridge/archive/refs/heads/main.zip
28
+ ```
29
+
30
+ To install with optional **Polars** acceleration support:
31
+
32
+ ```bash
33
+ pip install "calbridge[polars] @ https://github.com/bistoonh/calbridge/archive/refs/heads/main.zip"
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Examples
39
+
40
+ ```python
41
+ from calbridge import (
42
+ normalize_date,
43
+ convert_date,
44
+ day2day,
45
+ date_diff,
46
+ date_time_diff,
47
+ )
48
+
49
+ # 1. Normalize dates (Jalali)
50
+ normalize_date(["14020101", "1402-01", "1402-01-01 14:30:00"])
51
+ # ['1402-01-01', '1402-01-01', '1402-01-01 14:30:00']
52
+
53
+ # Single string input returns a string
54
+ normalize_date("14020101")
55
+ # '1402-01-01'
56
+
57
+
58
+ # 2. Convert Jalali to Gregorian
59
+ convert_date("1402-01-01", from_cal="j", to_cal="g")
60
+ # '2023-03-21'
61
+
62
+ # Convert Gregorian to Hijri
63
+ convert_date("2023-03-21", from_cal="g", to_cal="h")
64
+ # '1444-08-29'
65
+
66
+ # Vectorized conversions
67
+ dates = ["1402-01-01", "1402-05-15", "1402-12-29"]
68
+ convert_date(dates, from_cal="j", to_cal="g")
69
+ # ['2023-03-21', '2023-08-06', '2024-03-18']
70
+
71
+
72
+ # 3. Generate a sequence of Hijri dates
73
+ day2day("1447-09-01", "1447-09-03", calendar="h")
74
+ # ['1447-09-01', '1447-09-02', '1447-09-03']
75
+
76
+ # Include start and end times (only attached at endpoints)
77
+ day2day("2025-03-21 08:00:00", "2025-03-23 18:00:00", calendar="g")
78
+ # ['2025-03-21 08:00:00', '2025-03-22', '2025-03-23 18:00:00']
79
+
80
+
81
+ # 4. Compute day differences (Gregorian)
82
+ date_diff("2025-03-21", "2025-03-25", calendar="g")
83
+ # 4
84
+
85
+ # Vectorized day differences (Hijri)
86
+ date_diff(
87
+ ["1447-09-01", "1447-09-05"],
88
+ ["1447-09-03", "1447-09-10"],
89
+ calendar="h",
90
+ )
91
+ # [2, 5]
92
+
93
+
94
+ # 5. Compute date-time differences (seconds + formatted)
95
+ res = date_time_diff("1402-01-01 12:00:00", "1402-01-02 14:30:00", calendar="j")
96
+ print(res["seconds"])
97
+ # 95400
98
+
99
+ print(res["formatted"])
100
+ # '1 days 02:30:00'
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Data
106
+
107
+ The package includes a **pre-indexed calendar mapping** covering 1700 to 2200 CE:
108
+
109
+ ```python
110
+ from calbridge.normalize_date import _get_calendar_map
111
+
112
+ df = _get_calendar_map()
113
+ # Returns a Polars DataFrame (if installed) or Pandas DataFrame
114
+ ```
115
+
116
+ This table maps Jalali, Gregorian, and Hijri dates across multiple centuries, allowing instant O(1) lookups and fast vectorized joins without recalculating leap years or month structures on every call.
117
+
118
+ ---
119
+
120
+ ## Calendar Identifier Aliases
121
+
122
+ All functions accept both full names and short aliases:
123
+ - **Jalali / Shamsi:** `"j"`, `"jalali"`
124
+ - **Gregorian:** `"g"`, `"gregorian"`
125
+ - **Hijri:** `"h"`, `"hijri"`
126
+
127
+ ---
128
+
129
+ ## License
130
+
131
+ MIT License
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "calbridgepy"
7
+ version = "0.1.1"
8
+ description = "Fast date conversion and difference functions for Jalali, Gregorian, and Hijri calendars"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Bistoon Hosseini", email = "bistoon.hosseini@gmail.com" }
14
+ ]
15
+ dependencies = [
16
+ "pandas>=1.5"
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ polars = ["polars>=0.20"]
21
+
22
+ [tool.setuptools]
23
+ package-dir = {"" = "src"}
24
+ include-package-data = true
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.setuptools.package-data]
30
+ "calbridge" = ["data/*.pkl"]
31
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,15 @@
1
+ from .normalize_date import normalize_date
2
+ from .convert_date import convert_date
3
+ from .date_diff import date_diff
4
+ from .date_time_diff import date_time_diff
5
+ from .day2day import day2day
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "normalize_date",
11
+ "convert_date",
12
+ "date_diff",
13
+ "date_time_diff",
14
+ "day2day",
15
+ ]
@@ -0,0 +1,165 @@
1
+ from functools import lru_cache
2
+ from .normalize_date import _get_calendar_map, normalize_date
3
+
4
+ try:
5
+ import polars as pl
6
+ except ImportError:
7
+ pl = None
8
+
9
+ if pl is None:
10
+ import pandas as pd
11
+
12
+
13
+ _CALENDARS = {
14
+ "j": "Shamsi",
15
+ "jalali": "Shamsi",
16
+ "g": "Gregorian",
17
+ "gregorian": "Gregorian",
18
+ "h": "Hijri",
19
+ "hijri": "Hijri",
20
+ }
21
+
22
+
23
+ def _normalize_calendar(name):
24
+ """Validate and normalize calendar name input."""
25
+ if not isinstance(name, str) or name.lower() not in _CALENDARS:
26
+ raise ValueError(
27
+ "Unsupported calendar type. Use 'jalali'/'j', "
28
+ "'gregorian'/'g', or 'hijri'/'h'."
29
+ )
30
+ return _CALENDARS[name.lower()]
31
+
32
+
33
+ def _is_scalar(x):
34
+ """Check if input is a scalar value."""
35
+ return isinstance(x, (str, bytes)) or not hasattr(x, "__iter__")
36
+
37
+
38
+ @lru_cache(maxsize=12)
39
+ def _get_scalar_dict(from_col, to_col):
40
+ """Cache O(1) Python dictionary for lightning-fast scalar lookups."""
41
+ calendar_map = _get_calendar_map()
42
+ if pl is not None:
43
+ src = calendar_map.get_column(from_col).to_list()
44
+ dst = calendar_map.get_column(to_col).to_list()
45
+ else:
46
+ src = calendar_map[from_col].tolist()
47
+ dst = calendar_map[to_col].tolist()
48
+
49
+ # Built in reverse order so the first occurrence wins (equivalent to keep='first')
50
+ mapping = {}
51
+ for k, v in zip(reversed(src), reversed(dst)):
52
+ mapping[k] = v
53
+ return mapping
54
+
55
+
56
+ @lru_cache(maxsize=12)
57
+ def _get_polars_mapping(from_col, to_col):
58
+ """Pre-computed cached unique mapping table for Polars join."""
59
+ calendar_map = _get_calendar_map()
60
+ return calendar_map.select(
61
+ pl.col(from_col).alias("date"),
62
+ pl.col(to_col).alias("converted"),
63
+ ).unique(subset="date", keep="first", maintain_order=True)
64
+
65
+
66
+ @lru_cache(maxsize=12)
67
+ def _get_pandas_mapping(from_col, to_col):
68
+ """Pre-computed cached unique mapping table for Pandas merge."""
69
+ calendar_map = _get_calendar_map()
70
+ return (
71
+ calendar_map[[from_col, to_col]]
72
+ .rename(columns={from_col: "date", to_col: "converted"})
73
+ .drop_duplicates(subset="date", keep="first")
74
+ )
75
+
76
+
77
+ def convert_date(dates, from_cal, to_cal):
78
+ """Convert dates between Shamsi, Gregorian, and Hijri calendars.
79
+
80
+ Parameters:
81
+ -----------
82
+ dates : str, list, or array-like
83
+ Date strings or timestamps to convert.
84
+ from_cal : str
85
+ Source calendar ('jalali'/'j', 'gregorian'/'g', 'hijri'/'h').
86
+ to_cal : str
87
+ Target calendar ('jalali'/'j', 'gregorian'/'g', 'hijri'/'h').
88
+
89
+ Returns:
90
+ --------
91
+ str, list, or None
92
+ Converted date(s) preserving time components if present.
93
+ """
94
+ from_col = _normalize_calendar(from_cal)
95
+ to_col = _normalize_calendar(to_cal)
96
+
97
+ if from_col == to_col:
98
+ raise ValueError("'from' and 'to' calendars must be different.")
99
+
100
+ is_scalar = _is_scalar(dates)
101
+
102
+ # 1. Fast path for scalar input
103
+ if is_scalar:
104
+ norm_val = normalize_date(dates)
105
+ if norm_val is None:
106
+ return None
107
+
108
+ scalar_map = _get_scalar_dict(from_col, to_col)
109
+ if " " in norm_val:
110
+ d_part, t_part = norm_val.split(" ", 1)
111
+ converted = scalar_map.get(d_part)
112
+ return f"{converted} {t_part}" if converted is not None else None
113
+ else:
114
+ return scalar_map.get(norm_val)
115
+
116
+ # 2. Vectorized list / array path
117
+ values = normalize_date(dates)
118
+ if not values:
119
+ return []
120
+
121
+ if pl is not None:
122
+ df_input = pl.DataFrame({"original": values}, schema={"original": pl.Utf8})
123
+ split_df = df_input.with_columns(
124
+ split_struct=pl.col("original").str.splitn(" ", 2)
125
+ ).with_columns(
126
+ date=pl.col("split_struct").struct.field("field_0"),
127
+ time=pl.col("split_struct").struct.field("field_1"),
128
+ ).drop("split_struct")
129
+
130
+ mapping = _get_polars_mapping(from_col, to_col)
131
+
132
+ result = (
133
+ split_df
134
+ .join(mapping, on="date", how="left")
135
+ .with_columns(
136
+ final_res=pl.when(
137
+ pl.col("converted").is_not_null() &
138
+ pl.col("time").is_not_null() &
139
+ (pl.col("time") != "")
140
+ )
141
+ .then(pl.col("converted") + " " + pl.col("time"))
142
+ .otherwise(pl.col("converted"))
143
+ )
144
+ .get_column("final_res")
145
+ .to_list()
146
+ )
147
+ return result
148
+
149
+ else:
150
+ source_series = pd.Series(values, dtype="object")
151
+ split_df = source_series.str.split(" ", n=1, expand=True)
152
+ date_only = split_df[0]
153
+ time_only = split_df[1] if 1 in split_df.columns else pd.Series([None] * len(values))
154
+
155
+ mapping = _get_pandas_mapping(from_col, to_col)
156
+
157
+ merged = pd.DataFrame({"date": date_only}).merge(mapping, on="date", how="left")
158
+ converted = merged["converted"]
159
+
160
+ mask = converted.notna() & time_only.notna() & (time_only != "")
161
+ result_series = converted.copy()
162
+ result_series[mask] = converted[mask] + " " + time_only[mask]
163
+ result_series[~converted.notna()] = None
164
+
165
+ return result_series.tolist()
@@ -0,0 +1,181 @@
1
+ from functools import lru_cache
2
+
3
+ try:
4
+ import polars as pl
5
+ except ImportError:
6
+ pl = None
7
+
8
+ if pl is None:
9
+ import pandas as pd
10
+
11
+ from .normalize_date import _get_calendar_map, _is_missing, normalize_date
12
+
13
+
14
+ _CALENDAR_COLUMNS = {
15
+ "j": "Shamsi",
16
+ "jalali": "Shamsi",
17
+ "g": "Gregorian",
18
+ "gregorian": "Gregorian",
19
+ "h": "Hijri",
20
+ "hijri": "Hijri",
21
+ }
22
+
23
+
24
+ def _normalize_calendar(calendar):
25
+ if not isinstance(calendar, str):
26
+ raise ValueError(
27
+ "Unsupported calendar type. Use 'jalali'/'j', "
28
+ "'gregorian'/'g', or 'hijri'/'h'."
29
+ )
30
+
31
+ column = _CALENDAR_COLUMNS.get(calendar.lower())
32
+
33
+ if column is None:
34
+ raise ValueError(
35
+ "Unsupported calendar type. Use 'jalali'/'j', "
36
+ "'gregorian'/'g', or 'hijri'/'h'."
37
+ )
38
+
39
+ return column
40
+
41
+
42
+ def _as_list(value):
43
+ """Accept either one date or an iterable of dates."""
44
+ if isinstance(value, (str, bytes)) or not hasattr(value, "__iter__"):
45
+ return [value], True
46
+
47
+ return list(value), False
48
+
49
+
50
+ @lru_cache(maxsize=3)
51
+ def _get_date_index_dict(column):
52
+ """Pre-compute date to day index mapping for O(1) lookups."""
53
+ calendar_map = _get_calendar_map()
54
+ if pl is not None:
55
+ dates = calendar_map.get_column(column).to_list()
56
+ else:
57
+ dates = calendar_map[column].tolist()
58
+
59
+ # Built in reverse order so the first occurrence index wins
60
+ mapping = {}
61
+ total = len(dates)
62
+ for i in range(total - 1, -1, -1):
63
+ mapping[dates[i]] = i
64
+ return mapping
65
+
66
+
67
+ @lru_cache(maxsize=3)
68
+ def _get_polars_index_mapping(column):
69
+ """Cached mapping dataframe with day indices for Polars joins."""
70
+ calendar_map = _get_calendar_map()
71
+ return (
72
+ calendar_map
73
+ .with_row_index("day_index")
74
+ .select(
75
+ pl.col(column).alias("date"),
76
+ pl.col("day_index").cast(pl.Int64),
77
+ )
78
+ .unique(subset="date", keep="first", maintain_order=True)
79
+ )
80
+
81
+
82
+ def date_diff(start_date, end_date, calendar):
83
+ """Return end_date - start_date in calendar days.
84
+
85
+ Missing, invalid, or unmatched dates produce None.
86
+ A scalar pair returns a scalar; iterables return a list.
87
+ """
88
+ column = _normalize_calendar(calendar)
89
+
90
+ starts, start_is_scalar = _as_list(start_date)
91
+ ends, end_is_scalar = _as_list(end_date)
92
+
93
+ if len(starts) != len(ends):
94
+ raise ValueError(
95
+ "Lengths of start_date and end_date must be equal."
96
+ )
97
+
98
+ if not starts:
99
+ return []
100
+
101
+ both_scalar = start_is_scalar and end_is_scalar
102
+
103
+ # --- 1. Ultra-fast scalar path ---
104
+ if both_scalar:
105
+ s_val = starts[0]
106
+ e_val = ends[0]
107
+ if _is_missing(s_val) or _is_missing(e_val) or s_val == "" or e_val == "":
108
+ return None
109
+
110
+ s_norm = normalize_date(s_val)
111
+ e_norm = normalize_date(e_val)
112
+ if s_norm is None or e_norm is None:
113
+ return None
114
+
115
+ # Extract only the date part if time component is attached
116
+ s_date = s_norm.split(" ", 1)[0]
117
+ e_date = e_norm.split(" ", 1)[0]
118
+
119
+ idx_map = _get_date_index_dict(column)
120
+ s_idx = idx_map.get(s_date)
121
+ e_idx = idx_map.get(e_date)
122
+
123
+ if s_idx is None or e_idx is None:
124
+ return None
125
+ return e_idx - s_idx
126
+
127
+ # --- 2. Vectorized list / array path ---
128
+ # Normalize inputs while preserving positions
129
+ s_clean = [None if (_is_missing(x) or str(x) == "") else x for x in starts]
130
+ e_clean = [None if (_is_missing(x) or str(x) == "") else x for x in ends]
131
+
132
+ s_norm = normalize_date(s_clean)
133
+ e_norm = normalize_date(e_clean)
134
+
135
+ if pl is not None:
136
+ mapping = _get_polars_index_mapping(column)
137
+
138
+ # Prepare start and end series, extracting the date part
139
+ df = pl.DataFrame({
140
+ "s_raw": s_norm,
141
+ "e_raw": e_norm,
142
+ }, schema={"s_raw": pl.Utf8, "e_raw": pl.Utf8}).with_columns(
143
+ s_date=pl.col("s_raw").str.splitn(" ", 2).struct.field("field_0"),
144
+ e_date=pl.col("e_raw").str.splitn(" ", 2).struct.field("field_0"),
145
+ )
146
+
147
+ result = (
148
+ df
149
+ .join(mapping.rename({"date": "s_date", "day_index": "s_idx"}), on="s_date", how="left")
150
+ .join(mapping.rename({"date": "e_date", "day_index": "e_idx"}), on="e_date", how="left")
151
+ .with_columns(
152
+ diff_res=pl.when(
153
+ pl.col("s_idx").is_not_null() & pl.col("e_idx").is_not_null()
154
+ )
155
+ .then(pl.col("e_idx") - pl.col("s_idx"))
156
+ .otherwise(None)
157
+ )
158
+ .get_column("diff_res")
159
+ .to_list()
160
+ )
161
+ return result
162
+
163
+ else:
164
+ # Fallback using cached dictionary (faster than pandas merge)
165
+ idx_map = _get_date_index_dict(column)
166
+ result = []
167
+ append = result.append
168
+ for s, e in zip(s_norm, e_norm):
169
+ if s is None or e is None:
170
+ append(None)
171
+ continue
172
+ s_d = s.split(" ", 1)[0]
173
+ e_d = e.split(" ", 1)[0]
174
+ s_idx = idx_map.get(s_d)
175
+ e_idx = idx_map.get(e_d)
176
+ if s_idx is None or e_idx is None:
177
+ append(None)
178
+ else:
179
+ append(e_idx - s_idx)
180
+
181
+ return result