calbridgepy 0.2.0__py3-none-any.whl
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.
- calbridgepy/__init__.py +15 -0
- calbridgepy/convert_date.py +165 -0
- calbridgepy/data/calendar_map.pkl +0 -0
- calbridgepy/date_diff.py +181 -0
- calbridgepy/date_time_diff.py +297 -0
- calbridgepy/day2day.py +146 -0
- calbridgepy/normalize_date.py +287 -0
- calbridgepy-0.2.0.dist-info/METADATA +155 -0
- calbridgepy-0.2.0.dist-info/RECORD +12 -0
- calbridgepy-0.2.0.dist-info/WHEEL +5 -0
- calbridgepy-0.2.0.dist-info/licenses/LICENSE +21 -0
- calbridgepy-0.2.0.dist-info/top_level.txt +1 -0
calbridgepy/__init__.py
ADDED
|
@@ -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.2.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()
|
|
Binary file
|
calbridgepy/date_diff.py
ADDED
|
@@ -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
|
|
@@ -0,0 +1,297 @@
|
|
|
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, 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
|
+
_DEFAULT_TIME = "00:00:00"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _normalize_calendar(calendar):
|
|
27
|
+
"""Normalize and validate the calendar name."""
|
|
28
|
+
if not isinstance(calendar, str):
|
|
29
|
+
raise ValueError(
|
|
30
|
+
"Unsupported calendar type. Use 'jalali'/'j', "
|
|
31
|
+
"'gregorian'/'g', or 'hijri'/'h'."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
column = _CALENDAR_COLUMNS.get(calendar.lower())
|
|
35
|
+
|
|
36
|
+
if column is None:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
"Unsupported calendar type. Use 'jalali'/'j', "
|
|
39
|
+
"'gregorian'/'g', or 'hijri'/'h'."
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
return column
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _as_list(value):
|
|
46
|
+
"""Convert a scalar or an iterable to a list."""
|
|
47
|
+
if isinstance(value, (str, bytes)) or not hasattr(value, "__iter__"):
|
|
48
|
+
return [value], True
|
|
49
|
+
|
|
50
|
+
return list(value), False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _split_datetime(value):
|
|
54
|
+
"""Split normalized datetime into date part and time part."""
|
|
55
|
+
if value is None:
|
|
56
|
+
return None, _DEFAULT_TIME
|
|
57
|
+
|
|
58
|
+
if " " not in value:
|
|
59
|
+
return value, _DEFAULT_TIME
|
|
60
|
+
|
|
61
|
+
date_part, time_part = value.split(" ", 1)
|
|
62
|
+
time_part = time_part.strip() or _DEFAULT_TIME
|
|
63
|
+
return date_part, time_part
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _to_int_or_zero(value):
|
|
67
|
+
try:
|
|
68
|
+
return int(value)
|
|
69
|
+
except (TypeError, ValueError):
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _time_to_seconds(value):
|
|
74
|
+
parts = str(value).split(":")
|
|
75
|
+
hour = _to_int_or_zero(parts[0]) if len(parts) > 0 else 0
|
|
76
|
+
minute = _to_int_or_zero(parts[1]) if len(parts) > 1 else 0
|
|
77
|
+
second = _to_int_or_zero(parts[2]) if len(parts) > 2 else 0
|
|
78
|
+
return hour * 3600 + minute * 60 + second
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _format_seconds(total_seconds):
|
|
82
|
+
if total_seconds is None:
|
|
83
|
+
return None
|
|
84
|
+
days, remainder = divmod(int(total_seconds), 86400)
|
|
85
|
+
hours, remainder = divmod(remainder, 3600)
|
|
86
|
+
minutes, seconds = divmod(remainder, 60)
|
|
87
|
+
return f"{days} days {hours:02d}:{minutes:02d}:{seconds:02d}"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@lru_cache(maxsize=3)
|
|
91
|
+
def _get_date_index_dict(column):
|
|
92
|
+
"""Cache date -> row index for O(1) lookup."""
|
|
93
|
+
calendar_map = _get_calendar_map()
|
|
94
|
+
|
|
95
|
+
if pl is not None:
|
|
96
|
+
dates = calendar_map.get_column(column).to_list()
|
|
97
|
+
else:
|
|
98
|
+
dates = calendar_map[column].tolist()
|
|
99
|
+
|
|
100
|
+
mapping = {}
|
|
101
|
+
for i in range(len(dates) - 1, -1, -1):
|
|
102
|
+
mapping[dates[i]] = i
|
|
103
|
+
|
|
104
|
+
return mapping
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@lru_cache(maxsize=3)
|
|
108
|
+
def _get_polars_index_mapping(column):
|
|
109
|
+
"""Cached Polars mapping dataframe for joins."""
|
|
110
|
+
calendar_map = _get_calendar_map()
|
|
111
|
+
return (
|
|
112
|
+
calendar_map
|
|
113
|
+
.with_row_index("day_index")
|
|
114
|
+
.select(
|
|
115
|
+
pl.col(column).alias("date"),
|
|
116
|
+
pl.col("day_index").cast(pl.Int64),
|
|
117
|
+
)
|
|
118
|
+
.unique(subset="date", keep="first", maintain_order=True)
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def date_time_diff(start_date, end_date, calendar):
|
|
123
|
+
"""Calculate date-time differences between two date-time inputs.
|
|
124
|
+
|
|
125
|
+
Returns
|
|
126
|
+
-------
|
|
127
|
+
dict
|
|
128
|
+
{"seconds": [...], "formatted": [...]}
|
|
129
|
+
|
|
130
|
+
Missing, invalid, or unmatched values produce None in both lists.
|
|
131
|
+
Date-only values are interpreted as midnight.
|
|
132
|
+
"""
|
|
133
|
+
starts, start_is_scalar = _as_list(start_date)
|
|
134
|
+
ends, end_is_scalar = _as_list(end_date)
|
|
135
|
+
|
|
136
|
+
if len(starts) != len(ends):
|
|
137
|
+
raise ValueError(
|
|
138
|
+
"Lengths of start_date and end_date must be equal."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
column = _normalize_calendar(calendar)
|
|
142
|
+
|
|
143
|
+
if not starts:
|
|
144
|
+
return {"seconds": [], "formatted": []}
|
|
145
|
+
|
|
146
|
+
both_scalar = start_is_scalar and end_is_scalar
|
|
147
|
+
|
|
148
|
+
# --- Ultra-fast scalar path ---
|
|
149
|
+
if both_scalar:
|
|
150
|
+
start_norm = normalize_date(starts[0])
|
|
151
|
+
end_norm = normalize_date(ends[0])
|
|
152
|
+
|
|
153
|
+
if start_norm is None or end_norm is None:
|
|
154
|
+
diff_seconds = [None]
|
|
155
|
+
return {
|
|
156
|
+
"seconds": diff_seconds,
|
|
157
|
+
"formatted": [_format_seconds(None)],
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
start_day, start_time = _split_datetime(start_norm)
|
|
161
|
+
end_day, end_time = _split_datetime(end_norm)
|
|
162
|
+
|
|
163
|
+
idx_map = _get_date_index_dict(column)
|
|
164
|
+
start_idx = idx_map.get(start_day)
|
|
165
|
+
end_idx = idx_map.get(end_day)
|
|
166
|
+
|
|
167
|
+
if start_idx is None or end_idx is None:
|
|
168
|
+
diff_seconds = [None]
|
|
169
|
+
else:
|
|
170
|
+
diff_seconds = [
|
|
171
|
+
(end_idx - start_idx) * 86400
|
|
172
|
+
+ _time_to_seconds(end_time)
|
|
173
|
+
- _time_to_seconds(start_time)
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
return {
|
|
177
|
+
"seconds": diff_seconds,
|
|
178
|
+
"formatted": [_format_seconds(diff_seconds[0])],
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
# --- Batch path ---
|
|
182
|
+
start_norm = normalize_date(starts)
|
|
183
|
+
end_norm = normalize_date(ends)
|
|
184
|
+
|
|
185
|
+
if pl is not None:
|
|
186
|
+
input_df = pl.DataFrame(
|
|
187
|
+
{
|
|
188
|
+
"start_raw": start_norm,
|
|
189
|
+
"end_raw": end_norm,
|
|
190
|
+
},
|
|
191
|
+
schema={"start_raw": pl.Utf8, "end_raw": pl.Utf8},
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
parsed_df = input_df.with_columns(
|
|
195
|
+
start_split=pl.col("start_raw").str.splitn(" ", 2),
|
|
196
|
+
end_split=pl.col("end_raw").str.splitn(" ", 2),
|
|
197
|
+
).with_columns(
|
|
198
|
+
start_day=pl.col("start_split").struct.field("field_0"),
|
|
199
|
+
start_time=pl.coalesce(
|
|
200
|
+
[
|
|
201
|
+
pl.col("start_split").struct.field("field_1").str.strip_chars(),
|
|
202
|
+
pl.lit(_DEFAULT_TIME),
|
|
203
|
+
]
|
|
204
|
+
),
|
|
205
|
+
end_day=pl.col("end_split").struct.field("field_0"),
|
|
206
|
+
end_time=pl.coalesce(
|
|
207
|
+
[
|
|
208
|
+
pl.col("end_split").struct.field("field_1").str.strip_chars(),
|
|
209
|
+
pl.lit(_DEFAULT_TIME),
|
|
210
|
+
]
|
|
211
|
+
),
|
|
212
|
+
).with_columns(
|
|
213
|
+
start_time=pl.when(pl.col("start_time") == "")
|
|
214
|
+
.then(pl.lit(_DEFAULT_TIME))
|
|
215
|
+
.otherwise(pl.col("start_time")),
|
|
216
|
+
end_time=pl.when(pl.col("end_time") == "")
|
|
217
|
+
.then(pl.lit(_DEFAULT_TIME))
|
|
218
|
+
.otherwise(pl.col("end_time")),
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
time_parsed = parsed_df.with_columns(
|
|
222
|
+
start_parts=pl.col("start_time").str.splitn(":", 3),
|
|
223
|
+
end_parts=pl.col("end_time").str.splitn(":", 3),
|
|
224
|
+
).with_columns(
|
|
225
|
+
start_h=pl.col("start_parts").struct.field("field_0").cast(pl.Int32, strict=False).fill_null(0),
|
|
226
|
+
start_m=pl.col("start_parts").struct.field("field_1").cast(pl.Int32, strict=False).fill_null(0),
|
|
227
|
+
start_s=pl.col("start_parts").struct.field("field_2").cast(pl.Int32, strict=False).fill_null(0),
|
|
228
|
+
end_h=pl.col("end_parts").struct.field("field_0").cast(pl.Int32, strict=False).fill_null(0),
|
|
229
|
+
end_m=pl.col("end_parts").struct.field("field_1").cast(pl.Int32, strict=False).fill_null(0),
|
|
230
|
+
end_s=pl.col("end_parts").struct.field("field_2").cast(pl.Int32, strict=False).fill_null(0),
|
|
231
|
+
).with_columns(
|
|
232
|
+
start_sec=(pl.col("start_h") * 3600 + pl.col("start_m") * 60 + pl.col("start_s")),
|
|
233
|
+
end_sec=(pl.col("end_h") * 3600 + pl.col("end_m") * 60 + pl.col("end_s")),
|
|
234
|
+
).drop(
|
|
235
|
+
"start_split", "end_split", "start_parts", "end_parts"
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
mapping = _get_polars_index_mapping(column)
|
|
239
|
+
|
|
240
|
+
diff_seconds = (
|
|
241
|
+
time_parsed
|
|
242
|
+
.join(
|
|
243
|
+
mapping.rename({"date": "start_day", "day_index": "start_idx"}),
|
|
244
|
+
on="start_day",
|
|
245
|
+
how="left",
|
|
246
|
+
)
|
|
247
|
+
.join(
|
|
248
|
+
mapping.rename({"date": "end_day", "day_index": "end_idx"}),
|
|
249
|
+
on="end_day",
|
|
250
|
+
how="left",
|
|
251
|
+
)
|
|
252
|
+
.with_columns(
|
|
253
|
+
diff_res=pl.when(
|
|
254
|
+
pl.col("start_idx").is_not_null() & pl.col("end_idx").is_not_null()
|
|
255
|
+
)
|
|
256
|
+
.then(
|
|
257
|
+
(pl.col("end_idx") - pl.col("start_idx")) * 86400
|
|
258
|
+
+ pl.col("end_sec")
|
|
259
|
+
- pl.col("start_sec")
|
|
260
|
+
)
|
|
261
|
+
.otherwise(None)
|
|
262
|
+
)
|
|
263
|
+
.get_column("diff_res")
|
|
264
|
+
.to_list()
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
else:
|
|
268
|
+
idx_map = _get_date_index_dict(column)
|
|
269
|
+
|
|
270
|
+
diff_seconds = []
|
|
271
|
+
append = diff_seconds.append
|
|
272
|
+
|
|
273
|
+
for start_value, end_value in zip(start_norm, end_norm):
|
|
274
|
+
if start_value is None or end_value is None:
|
|
275
|
+
append(None)
|
|
276
|
+
continue
|
|
277
|
+
|
|
278
|
+
start_day, start_time = _split_datetime(start_value)
|
|
279
|
+
end_day, end_time = _split_datetime(end_value)
|
|
280
|
+
|
|
281
|
+
start_idx = idx_map.get(start_day)
|
|
282
|
+
end_idx = idx_map.get(end_day)
|
|
283
|
+
|
|
284
|
+
if start_idx is None or end_idx is None:
|
|
285
|
+
append(None)
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
append(
|
|
289
|
+
(end_idx - start_idx) * 86400
|
|
290
|
+
+ _time_to_seconds(end_time)
|
|
291
|
+
- _time_to_seconds(start_time)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
"seconds": diff_seconds,
|
|
296
|
+
"formatted": [_format_seconds(value) for value in diff_seconds],
|
|
297
|
+
}
|
calbridgepy/day2day.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
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, 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
|
+
"""Normalize and validate the calendar name."""
|
|
26
|
+
if not isinstance(calendar, str):
|
|
27
|
+
raise ValueError(
|
|
28
|
+
"Unsupported calendar type. Use 'jalali'/'j', "
|
|
29
|
+
"'gregorian'/'g', or 'hijri'/'h'."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
column = _CALENDAR_COLUMNS.get(calendar.lower())
|
|
33
|
+
|
|
34
|
+
if column is None:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
"Unsupported calendar type. Use 'jalali'/'j', "
|
|
37
|
+
"'gregorian'/'g', or 'hijri'/'h'."
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return column
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _as_list(value):
|
|
44
|
+
"""Convert a scalar or an iterable to a list."""
|
|
45
|
+
if isinstance(value, (str, bytes)) or not hasattr(value, "__iter__"):
|
|
46
|
+
return [value]
|
|
47
|
+
|
|
48
|
+
return list(value)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _split_datetime(value):
|
|
52
|
+
"""Split a normalized date-time into date and optional time."""
|
|
53
|
+
if " " not in value:
|
|
54
|
+
return value, None
|
|
55
|
+
|
|
56
|
+
date_part, time_part = value.split(" ", 1)
|
|
57
|
+
time_part = time_part.strip() or None
|
|
58
|
+
|
|
59
|
+
return date_part, time_part
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@lru_cache(maxsize=3)
|
|
63
|
+
def _get_cached_calendar_data(column):
|
|
64
|
+
"""Cache the unique date vector and O(1) index map for each calendar."""
|
|
65
|
+
calendar_map = _get_calendar_map()
|
|
66
|
+
|
|
67
|
+
if pl is not None and isinstance(calendar_map, pl.DataFrame):
|
|
68
|
+
unique_dates = (
|
|
69
|
+
calendar_map
|
|
70
|
+
.select(pl.col(column).alias("date"))
|
|
71
|
+
.unique(subset="date", keep="first", maintain_order=True)
|
|
72
|
+
.get_column("date")
|
|
73
|
+
.to_list()
|
|
74
|
+
)
|
|
75
|
+
else:
|
|
76
|
+
values = calendar_map[column].tolist()
|
|
77
|
+
unique_dates = []
|
|
78
|
+
seen = set()
|
|
79
|
+
for v in values:
|
|
80
|
+
if v is not None and v == v and v not in seen:
|
|
81
|
+
seen.add(v)
|
|
82
|
+
unique_dates.append(str(v))
|
|
83
|
+
|
|
84
|
+
date_index = {date: idx for idx, date in enumerate(unique_dates)}
|
|
85
|
+
return unique_dates, date_index
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def day2day(start_date, end_date, calendar):
|
|
89
|
+
"""Generate all calendar dates between two dates (inclusive).
|
|
90
|
+
|
|
91
|
+
If an input has several elements, only the first is used (as in R),
|
|
92
|
+
but all elements must be valid after normalization.
|
|
93
|
+
|
|
94
|
+
If either endpoint has a time, the start time is attached to the
|
|
95
|
+
first result and the end time to the last one. For a single-day
|
|
96
|
+
range, the end time overrides the start time (as in R).
|
|
97
|
+
"""
|
|
98
|
+
column = _normalize_calendar(calendar)
|
|
99
|
+
|
|
100
|
+
# Normalize start and end
|
|
101
|
+
start_norm_all = _as_list(normalize_date(start_date))
|
|
102
|
+
end_norm_all = _as_list(normalize_date(end_date))
|
|
103
|
+
|
|
104
|
+
if (
|
|
105
|
+
not start_norm_all
|
|
106
|
+
or not end_norm_all
|
|
107
|
+
or any(v is None for v in start_norm_all)
|
|
108
|
+
or any(v is None for v in end_norm_all)
|
|
109
|
+
):
|
|
110
|
+
raise ValueError("Invalid start or end date after normalization.")
|
|
111
|
+
|
|
112
|
+
start_date_only, start_time = _split_datetime(start_norm_all[0])
|
|
113
|
+
end_date_only, end_time = _split_datetime(end_norm_all[0])
|
|
114
|
+
|
|
115
|
+
date_vector, date_index = _get_cached_calendar_data(column)
|
|
116
|
+
|
|
117
|
+
idx_start = date_index.get(start_date_only)
|
|
118
|
+
idx_end = date_index.get(end_date_only)
|
|
119
|
+
|
|
120
|
+
if idx_start is None or idx_end is None:
|
|
121
|
+
raise ValueError("Start or end date not found in mapping table.")
|
|
122
|
+
|
|
123
|
+
# Slice the pre-allocated vector directly
|
|
124
|
+
if idx_start <= idx_end:
|
|
125
|
+
result_dates = date_vector[idx_start:idx_end + 1]
|
|
126
|
+
else:
|
|
127
|
+
result_dates = date_vector[idx_end:idx_start + 1][::-1]
|
|
128
|
+
|
|
129
|
+
# If neither boundary has a time component, return sliced dates directly
|
|
130
|
+
if start_time is None and end_time is None:
|
|
131
|
+
return result_dates
|
|
132
|
+
|
|
133
|
+
# Shallow copy to modify endpoints without mutating the cached vector
|
|
134
|
+
result = list(result_dates)
|
|
135
|
+
|
|
136
|
+
# Same logic as R:
|
|
137
|
+
# 1. Attach start_time to first element if present
|
|
138
|
+
if start_time is not None:
|
|
139
|
+
result[0] = f"{result[0]} {start_time}"
|
|
140
|
+
|
|
141
|
+
# 2. Attach end_time to last element if present (overrides start_time if len == 1)
|
|
142
|
+
if end_time is not None:
|
|
143
|
+
raw_last = result_dates[-1]
|
|
144
|
+
result[-1] = f"{raw_last} {end_time}"
|
|
145
|
+
|
|
146
|
+
return result
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import pickle
|
|
3
|
+
import re
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import polars as pl
|
|
9
|
+
except ImportError:
|
|
10
|
+
pl = None
|
|
11
|
+
|
|
12
|
+
if pl is None:
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_DATE_8 = re.compile(r"^[0-9]{8}$")
|
|
17
|
+
_DATE_6 = re.compile(r"^[0-9]{6}$")
|
|
18
|
+
_DATE_PADDED = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
|
|
19
|
+
_DATE_PARTIAL = re.compile(r"^[0-9]{4}-[0-9]{1,2}(?:-[0-9]{1,2})?$")
|
|
20
|
+
|
|
21
|
+
_COLUMNS = ("Shamsi", "Gregorian", "Hijri")
|
|
22
|
+
|
|
23
|
+
@lru_cache(maxsize=1)
|
|
24
|
+
def _get_calendar_map():
|
|
25
|
+
"""Load the bundled mapping once, using the available backend.
|
|
26
|
+
|
|
27
|
+
All columns are cast to strings.
|
|
28
|
+
"""
|
|
29
|
+
resource = files("calbridgepy").joinpath("data", "calendar_map.pkl")
|
|
30
|
+
|
|
31
|
+
with resource.open("rb") as f:
|
|
32
|
+
data = pickle.load(f)
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
missing = [col for col in _COLUMNS if col not in data]
|
|
36
|
+
if missing:
|
|
37
|
+
raise KeyError(missing)
|
|
38
|
+
columns = {
|
|
39
|
+
col: [str(x) for x in list(data[col])] for col in _COLUMNS
|
|
40
|
+
}
|
|
41
|
+
except (TypeError, KeyError):
|
|
42
|
+
raise ValueError(
|
|
43
|
+
"calendar_map.pkl must contain Shamsi, Gregorian, "
|
|
44
|
+
"and Hijri columns."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if pl is not None:
|
|
48
|
+
return pl.DataFrame(columns).with_columns(
|
|
49
|
+
[pl.col(col).cast(pl.Utf8) for col in _COLUMNS]
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
return pd.DataFrame(columns).astype(str)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@lru_cache(maxsize=1)
|
|
56
|
+
def _get_valid_dates():
|
|
57
|
+
"""Cache the valid dates across all three calendars as a set."""
|
|
58
|
+
calendar_map = _get_calendar_map()
|
|
59
|
+
|
|
60
|
+
if pl is not None:
|
|
61
|
+
dates = (
|
|
62
|
+
pl.concat([calendar_map.get_column(col) for col in _COLUMNS])
|
|
63
|
+
.unique()
|
|
64
|
+
.to_list()
|
|
65
|
+
)
|
|
66
|
+
else:
|
|
67
|
+
dates = pd.unique(
|
|
68
|
+
calendar_map[list(_COLUMNS)].to_numpy().ravel()
|
|
69
|
+
).tolist()
|
|
70
|
+
|
|
71
|
+
return set(dates)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@lru_cache(maxsize=1)
|
|
75
|
+
def _get_valid_dates_polars_series():
|
|
76
|
+
"""Cache valid dates as a Polars Series for fast `is_in` lookup."""
|
|
77
|
+
if pl is None:
|
|
78
|
+
return None
|
|
79
|
+
return pl.Series("valid_dates", list(_get_valid_dates()), dtype=pl.Utf8)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_missing(value):
|
|
83
|
+
"""Return True for None, NaN, pandas NA and NaT."""
|
|
84
|
+
if value is None:
|
|
85
|
+
return True
|
|
86
|
+
if isinstance(value, float) and math.isnan(value):
|
|
87
|
+
return True
|
|
88
|
+
return type(value).__name__ in ("NAType", "NaTType")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _normalize_date_part_py(value):
|
|
92
|
+
"""Fallback Python helper for scalar or pandas normalization."""
|
|
93
|
+
if _DATE_8.fullmatch(value):
|
|
94
|
+
return f"{value[:4]}-{value[4:6]}-{value[6:8]}"
|
|
95
|
+
if _DATE_6.fullmatch(value):
|
|
96
|
+
return f"{value[:4]}-{value[4:6]}-01"
|
|
97
|
+
if _DATE_PADDED.fullmatch(value) or _DATE_PARTIAL.fullmatch(value):
|
|
98
|
+
parts = value.split("-")
|
|
99
|
+
year = parts[0]
|
|
100
|
+
month = int(parts[1])
|
|
101
|
+
day = int(parts[2]) if len(parts) == 3 else 1
|
|
102
|
+
return f"{year}-{month:02d}-{day:02d}"
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _normalize_time_part_py(value):
|
|
107
|
+
"""Fallback Python helper for time normalization."""
|
|
108
|
+
parts = value.split(":")
|
|
109
|
+
try:
|
|
110
|
+
hour = int(parts[0])
|
|
111
|
+
minute = int(parts[1]) if len(parts) > 1 else 0
|
|
112
|
+
second = int(parts[2]) if len(parts) > 2 else 0
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
if not (0 <= hour <= 23 and 0 <= minute <= 59 and 0 <= second <= 59):
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
return f"{hour:02d}:{minute:02d}:{second:02d}"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _normalize_scalar_date(value, valid_dates):
|
|
123
|
+
"""Ultra-fast scalar path with zero DataFrame overhead."""
|
|
124
|
+
if _is_missing(value):
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
text = str(value).strip()
|
|
128
|
+
if not text:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
text = text.replace("/", "-").replace(".", "-")
|
|
132
|
+
|
|
133
|
+
if " " in text:
|
|
134
|
+
d_part, t_part = text.split(" ", 1)
|
|
135
|
+
t_part = t_part.strip() or None
|
|
136
|
+
else:
|
|
137
|
+
d_part, t_part = text, None
|
|
138
|
+
|
|
139
|
+
if not d_part:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
norm_d = _normalize_date_part_py(d_part)
|
|
143
|
+
if norm_d not in valid_dates:
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
if t_part is None:
|
|
147
|
+
return norm_d
|
|
148
|
+
|
|
149
|
+
norm_t = _normalize_time_part_py(t_part)
|
|
150
|
+
return f"{norm_d} {norm_t}" if norm_t is not None else None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def normalize_date(dates):
|
|
154
|
+
"""Normalize date strings to 'YYYY-MM-DD' format, with optional time.
|
|
155
|
+
|
|
156
|
+
Supports both Polars and Pandas backends with vectorized acceleration.
|
|
157
|
+
"""
|
|
158
|
+
is_scalar = isinstance(dates, str) or _is_missing(dates)
|
|
159
|
+
valid_dates = _get_valid_dates()
|
|
160
|
+
|
|
161
|
+
if is_scalar:
|
|
162
|
+
return _normalize_scalar_date(dates, valid_dates)
|
|
163
|
+
|
|
164
|
+
if hasattr(dates, "tolist"):
|
|
165
|
+
raw_list = dates.tolist()
|
|
166
|
+
else:
|
|
167
|
+
raw_list = list(dates)
|
|
168
|
+
|
|
169
|
+
if not raw_list:
|
|
170
|
+
return []
|
|
171
|
+
|
|
172
|
+
if pl is not None:
|
|
173
|
+
raw_values = [None if _is_missing(v) else str(v) for v in raw_list]
|
|
174
|
+
valid_series = _get_valid_dates_polars_series()
|
|
175
|
+
|
|
176
|
+
df = pl.DataFrame({"raw": raw_values}, schema={"raw": pl.Utf8})
|
|
177
|
+
|
|
178
|
+
# 1. Clean delimiters and split date/time
|
|
179
|
+
cleaned = (
|
|
180
|
+
df.with_columns(
|
|
181
|
+
cleaned_raw=pl.col("raw")
|
|
182
|
+
.str.strip_chars()
|
|
183
|
+
.str.replace_all("/", "-")
|
|
184
|
+
.str.replace_all(r"\.", "-")
|
|
185
|
+
)
|
|
186
|
+
.with_columns(
|
|
187
|
+
split_parts=pl.col("cleaned_raw").str.splitn(" ", 2)
|
|
188
|
+
)
|
|
189
|
+
.with_columns(
|
|
190
|
+
date_raw=pl.col("split_parts").struct.field("field_0"),
|
|
191
|
+
time_raw=pl.col("split_parts").struct.field("field_1").str.strip_chars(),
|
|
192
|
+
)
|
|
193
|
+
.drop("split_parts")
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# 2. Date parsing (Fast vectorized branches)
|
|
197
|
+
# Handling: YYYYMMDD, YYYYMM, and hyphenated dates (YYYY-M-D or YYYY-M)
|
|
198
|
+
d_parts = pl.col("date_raw").str.split("-")
|
|
199
|
+
p0 = d_parts.list.get(0)
|
|
200
|
+
p1 = d_parts.list.get(1)
|
|
201
|
+
p2 = d_parts.list.get(2)
|
|
202
|
+
|
|
203
|
+
hyphen_norm = (
|
|
204
|
+
pl.when(d_parts.list.len() == 3)
|
|
205
|
+
.then(
|
|
206
|
+
p0 + "-" + p1.str.zfill(2) + "-" + p2.str.zfill(2)
|
|
207
|
+
)
|
|
208
|
+
.when(d_parts.list.len() == 2)
|
|
209
|
+
.then(
|
|
210
|
+
p0 + "-" + p1.str.zfill(2) + "-01"
|
|
211
|
+
)
|
|
212
|
+
.otherwise(pl.col("date_raw"))
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
norm_d = (
|
|
216
|
+
pl.when(pl.col("date_raw").is_null() | (pl.col("date_raw") == ""))
|
|
217
|
+
.then(None)
|
|
218
|
+
.when(pl.col("date_raw").str.contains(r"^[0-9]{8}$"))
|
|
219
|
+
.then(
|
|
220
|
+
pl.col("date_raw").str.slice(0, 4)
|
|
221
|
+
+ "-"
|
|
222
|
+
+ pl.col("date_raw").str.slice(4, 2)
|
|
223
|
+
+ "-"
|
|
224
|
+
+ pl.col("date_raw").str.slice(6, 2)
|
|
225
|
+
)
|
|
226
|
+
.when(pl.col("date_raw").str.contains(r"^[0-9]{6}$"))
|
|
227
|
+
.then(
|
|
228
|
+
pl.col("date_raw").str.slice(0, 4)
|
|
229
|
+
+ "-"
|
|
230
|
+
+ pl.col("date_raw").str.slice(4, 2)
|
|
231
|
+
+ "-01"
|
|
232
|
+
)
|
|
233
|
+
.when(pl.col("date_raw").str.contains(r"^[0-9]{4}-[0-9]{1,2}(?:-[0-9]{1,2})?$"))
|
|
234
|
+
.then(hyphen_norm)
|
|
235
|
+
.otherwise(pl.col("date_raw"))
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
# 3. Time parsing
|
|
239
|
+
t_parts = pl.col("time_raw").str.split(":")
|
|
240
|
+
t0 = t_parts.list.get(0).cast(pl.Int64, strict=False)
|
|
241
|
+
t1 = pl.coalesce([t_parts.list.get(1).cast(pl.Int64, strict=False), pl.lit(0)])
|
|
242
|
+
t2 = pl.coalesce([t_parts.list.get(2).cast(pl.Int64, strict=False), pl.lit(0)])
|
|
243
|
+
|
|
244
|
+
time_is_valid = (
|
|
245
|
+
pl.col("time_raw").is_not_null()
|
|
246
|
+
& (pl.col("time_raw") != "")
|
|
247
|
+
& (t_parts.list.len() >= 1)
|
|
248
|
+
& (t_parts.list.len() <= 3)
|
|
249
|
+
& t0.is_between(0, 23)
|
|
250
|
+
& t1.is_between(0, 59)
|
|
251
|
+
& t2.is_between(0, 59)
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
norm_t = (
|
|
255
|
+
t0.cast(pl.Utf8).str.zfill(2)
|
|
256
|
+
+ ":"
|
|
257
|
+
+ t1.cast(pl.Utf8).str.zfill(2)
|
|
258
|
+
+ ":"
|
|
259
|
+
+ t2.cast(pl.Utf8).str.zfill(2)
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
# 4. Assemble and check against valid dates
|
|
263
|
+
res_df = cleaned.with_columns(
|
|
264
|
+
norm_d=norm_d,
|
|
265
|
+
time_is_valid=time_is_valid,
|
|
266
|
+
norm_t=norm_t,
|
|
267
|
+
).with_columns(
|
|
268
|
+
date_is_valid=pl.col("norm_d").is_in(valid_series)
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
final_col = (
|
|
272
|
+
pl.when(pl.col("raw").is_null() | (~pl.col("date_is_valid")))
|
|
273
|
+
.then(None)
|
|
274
|
+
.when(pl.col("time_raw").is_null() | (pl.col("time_raw") == ""))
|
|
275
|
+
.then(pl.col("norm_d"))
|
|
276
|
+
.when(pl.col("time_is_valid"))
|
|
277
|
+
.then(pl.col("norm_d") + " " + pl.col("norm_t"))
|
|
278
|
+
.otherwise(None)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
return res_df.select(final_res=final_col).get_column("final_res").to_list()
|
|
282
|
+
|
|
283
|
+
else:
|
|
284
|
+
append = []
|
|
285
|
+
for value in raw_list:
|
|
286
|
+
append.append(_normalize_scalar_date(value, valid_dates))
|
|
287
|
+
return append
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: calbridgepy
|
|
3
|
+
Version: 0.2.0
|
|
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
|
+
# calbridgepy
|
|
16
|
+
|
|
17
|
+
**calbridgepy** 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
|
+
### From PyPI (Recommended)
|
|
39
|
+
|
|
40
|
+
Install the standard version via `pip`:
|
|
41
|
+
```bash
|
|
42
|
+
pip install calbridgepy
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
To install with optional **Polars** acceleration support:
|
|
46
|
+
```bash
|
|
47
|
+
pip install "calbridgepy[polars]"
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
You can also install directly from the GitHub repository:
|
|
51
|
+
```bash
|
|
52
|
+
pip install https://github.com/bistoonh/calbridgepy/archive/refs/heads/main.zip
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
To install with optional **Polars** acceleration support:
|
|
56
|
+
```bash
|
|
57
|
+
pip install "calbridgepy[polars] @ https://github.com/bistoonh/calbridgepy/archive/refs/heads/main.zip"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Examples
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from calbridgepy import (
|
|
66
|
+
normalize_date,
|
|
67
|
+
convert_date,
|
|
68
|
+
day2day,
|
|
69
|
+
date_diff,
|
|
70
|
+
date_time_diff,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# 1. Normalize dates (Jalali)
|
|
74
|
+
normalize_date(["14020101", "1402-01", "1402-01-01 14:30:00"])
|
|
75
|
+
# ['1402-01-01', '1402-01-01', '1402-01-01 14:30:00']
|
|
76
|
+
|
|
77
|
+
# Single string input returns a string
|
|
78
|
+
normalize_date("14020101")
|
|
79
|
+
# '1402-01-01'
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# 2. Convert Jalali to Gregorian
|
|
83
|
+
convert_date("1402-01-01", from_cal="j", to_cal="g")
|
|
84
|
+
# '2023-03-21'
|
|
85
|
+
|
|
86
|
+
# Convert Gregorian to Hijri
|
|
87
|
+
convert_date("2023-03-21", from_cal="g", to_cal="h")
|
|
88
|
+
# '1444-08-29'
|
|
89
|
+
|
|
90
|
+
# Vectorized conversions
|
|
91
|
+
dates = ["1402-01-01", "1402-05-15", "1402-12-29"]
|
|
92
|
+
convert_date(dates, from_cal="j", to_cal="g")
|
|
93
|
+
# ['2023-03-21', '2023-08-06', '2024-03-18']
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# 3. Generate a sequence of Hijri dates
|
|
97
|
+
day2day("1447-09-01", "1447-09-03", calendar="h")
|
|
98
|
+
# ['1447-09-01', '1447-09-02', '1447-09-03']
|
|
99
|
+
|
|
100
|
+
# Include start and end times (only attached at endpoints)
|
|
101
|
+
day2day("2025-03-21 08:00:00", "2025-03-23 18:00:00", calendar="g")
|
|
102
|
+
# ['2025-03-21 08:00:00', '2025-03-22', '2025-03-23 18:00:00']
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# 4. Compute day differences (Gregorian)
|
|
106
|
+
date_diff("2025-03-21", "2025-03-25", calendar="g")
|
|
107
|
+
# 4
|
|
108
|
+
|
|
109
|
+
# Vectorized day differences (Hijri)
|
|
110
|
+
date_diff(
|
|
111
|
+
["1447-09-01", "1447-09-05"],
|
|
112
|
+
["1447-09-03", "1447-09-10"],
|
|
113
|
+
calendar="h",
|
|
114
|
+
)
|
|
115
|
+
# [2, 5]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# 5. Compute date-time differences (seconds + formatted)
|
|
119
|
+
res = date_time_diff("1402-01-01 12:00:00", "1402-01-02 14:30:00", calendar="j")
|
|
120
|
+
print(res["seconds"])
|
|
121
|
+
# 95400
|
|
122
|
+
|
|
123
|
+
print(res["formatted"])
|
|
124
|
+
# '1 days 02:30:00'
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Data
|
|
130
|
+
|
|
131
|
+
The package includes a **pre-indexed calendar mapping** covering 1700 to 2200 CE:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from calbridgepy.normalize_date import _get_calendar_map
|
|
135
|
+
|
|
136
|
+
df = _get_calendar_map()
|
|
137
|
+
# Returns a Polars DataFrame (if installed) or Pandas DataFrame
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
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.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Calendar Identifier Aliases
|
|
145
|
+
|
|
146
|
+
All functions accept both full names and short aliases:
|
|
147
|
+
- **Jalali / Shamsi:** `"j"`, `"jalali"`
|
|
148
|
+
- **Gregorian:** `"g"`, `"gregorian"`
|
|
149
|
+
- **Hijri:** `"h"`, `"hijri"`
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
MIT License
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
calbridgepy/__init__.py,sha256=VNRZ9LCHk91vsM3--GX3MenRkKRrbbO09z8aLfv4UIU,336
|
|
2
|
+
calbridgepy/convert_date.py,sha256=6-vm50rRIXDCkEaIyr85NcodWY_pIn2i3r7xwE1HmSk,5369
|
|
3
|
+
calbridgepy/date_diff.py,sha256=1iBYdb9q1rpphOeUm52-VDnx9jXZVzMc9B8-VVKWD48,5483
|
|
4
|
+
calbridgepy/date_time_diff.py,sha256=lu_1Ja00Bfnyo4AdwO8RumXUvJjsipO7SEYepImR-AI,9419
|
|
5
|
+
calbridgepy/day2day.py,sha256=m8_yVuYGwZH4mCw_PYnt_nxC1tMe5QfPMrmSPCFqNYY,4469
|
|
6
|
+
calbridgepy/normalize_date.py,sha256=NN_k-pXgsDAd0oNsIyZ0RhCZBrCRlJBDDU3jD9TVzrU,8941
|
|
7
|
+
calbridgepy/data/calendar_map.pkl,sha256=eU-itAI66vJcv1NwSaIbPxf87LQNsxm1js4BPGuCghQ,7139182
|
|
8
|
+
calbridgepy-0.2.0.dist-info/licenses/LICENSE,sha256=m70eTN8HIlTO2jcFmg1yYVnKy88h7G7FTpm7m-o50GE,1094
|
|
9
|
+
calbridgepy-0.2.0.dist-info/METADATA,sha256=R9oD6C46iQrmF1gMRpoqgzALatjuV3PMobgVtvr7aJQ,4753
|
|
10
|
+
calbridgepy-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
calbridgepy-0.2.0.dist-info/top_level.txt,sha256=ldAleTsgTn0BPuPRP8dIvmWT7v-YLrR1CGobR-DxE6Y,12
|
|
12
|
+
calbridgepy-0.2.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
calbridgepy
|