UltraPython 1.8.5__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.
ultrapython/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .ultrapython import *
|
|
@@ -0,0 +1,757 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pickle
|
|
3
|
+
import re
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from collections import deque
|
|
6
|
+
from pandas import read_csv, concat, DataFrame, read_sql, read_excel, ExcelWriter, read_parquet, Timestamp, DateOffset, to_datetime
|
|
7
|
+
from numpy import issubdtype, integer, floating
|
|
8
|
+
from inspect import signature
|
|
9
|
+
from sqlalchemy import create_engine
|
|
10
|
+
from openpyxl import load_workbook
|
|
11
|
+
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
|
12
|
+
from os.path import exists
|
|
13
|
+
from os import makedirs
|
|
14
|
+
from pyarrow.parquet import write_to_dataset
|
|
15
|
+
from pyarrow import Table
|
|
16
|
+
|
|
17
|
+
data_structures=(list, tuple, set, frozenset, deque)
|
|
18
|
+
data_types=(str, int, float, bool)
|
|
19
|
+
csvread_parameters=[i for i in signature(read_csv).parameters]
|
|
20
|
+
csvrewrite_parameters=[i for i in signature(DataFrame.to_csv).parameters]
|
|
21
|
+
excelread_parameters=[i for i in signature(read_excel).parameters]
|
|
22
|
+
|
|
23
|
+
colors={
|
|
24
|
+
'black': '000000',
|
|
25
|
+
'white': 'FFFFFF',
|
|
26
|
+
'red': 'FF0000',
|
|
27
|
+
'lime': '00FF00',
|
|
28
|
+
'blue': '0000FF',
|
|
29
|
+
'yellow': 'FFFF00',
|
|
30
|
+
'cyan': '00FFFF',
|
|
31
|
+
'grey': 'A9A9A9',
|
|
32
|
+
'green': '008000',
|
|
33
|
+
'orange': 'FFA500',
|
|
34
|
+
'brown': '8B4513',
|
|
35
|
+
'purple': '800080'
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type_formats={
|
|
39
|
+
'category': '@',
|
|
40
|
+
'object': '@',
|
|
41
|
+
'integer': '#,##0',
|
|
42
|
+
'float': '#,##0.##',
|
|
43
|
+
'default': 'General'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
timezones = {
|
|
47
|
+
'utc': 'UTC',
|
|
48
|
+
'gmt': 'GMT',
|
|
49
|
+
'ashgabat': 'Asia/Ashgabat',
|
|
50
|
+
'turkmenistan': 'Asia/Ashgabat',
|
|
51
|
+
'tmt': 'Asia/Ashgabat',
|
|
52
|
+
'tashkent': 'Asia/Tashkent',
|
|
53
|
+
'uzbekistan': 'Asia/Tashkent',
|
|
54
|
+
'almaty': 'Asia/Almaty',
|
|
55
|
+
'astana': 'Asia/Almaty',
|
|
56
|
+
'kazakhstan': 'Asia/Almaty',
|
|
57
|
+
'bishkek': 'Asia/Bishkek',
|
|
58
|
+
'dushanbe': 'Asia/Dushanbe',
|
|
59
|
+
'baku': 'Asia/Baku',
|
|
60
|
+
'yerevan': 'Asia/Yerevan',
|
|
61
|
+
'tbilisi': 'Asia/Tbilisi',
|
|
62
|
+
'minsk': 'Europe/Minsk',
|
|
63
|
+
'moscow': 'Europe/Moscow',
|
|
64
|
+
'msk': 'Europe/Moscow',
|
|
65
|
+
'yekaterinburg': 'Asia/Yekaterinburg',
|
|
66
|
+
'novosibirsk': 'Asia/Novosibirsk',
|
|
67
|
+
'vladivostok': 'Asia/Vladivostok',
|
|
68
|
+
'dubai': 'Asia/Dubai',
|
|
69
|
+
'uae': 'Asia/Dubai',
|
|
70
|
+
'istanbul': 'Europe/Istanbul',
|
|
71
|
+
'turkey': 'Europe/Istanbul',
|
|
72
|
+
'tehran': 'Asia/Tehran',
|
|
73
|
+
'beijing': 'Asia/Shanghai',
|
|
74
|
+
'china': 'Asia/Shanghai',
|
|
75
|
+
'tokyo': 'Asia/Tokyo',
|
|
76
|
+
'japan': 'Asia/Tokyo',
|
|
77
|
+
'seoul': 'Asia/Seoul',
|
|
78
|
+
'singapore': 'Asia/Singapore',
|
|
79
|
+
'delhi': 'Asia/Kolkata',
|
|
80
|
+
'india': 'Asia/Kolkata',
|
|
81
|
+
'london': 'Europe/London',
|
|
82
|
+
'uk': 'Europe/London',
|
|
83
|
+
'berlin': 'Europe/Berlin',
|
|
84
|
+
'paris': 'Europe/Paris',
|
|
85
|
+
'rome': 'Europe/Rome',
|
|
86
|
+
'madrid': 'Europe/Madrid',
|
|
87
|
+
'warsaw': 'Europe/Warsaw',
|
|
88
|
+
'new_york': 'America/New_York',
|
|
89
|
+
'est': 'America/New_York',
|
|
90
|
+
'chicago': 'America/Chicago',
|
|
91
|
+
'cst': 'America/Chicago',
|
|
92
|
+
'denver': 'America/Denver',
|
|
93
|
+
'mst': 'America/Denver',
|
|
94
|
+
'phoenix': 'America/Phoenix',
|
|
95
|
+
'los_angeles': 'America/Los_Angeles',
|
|
96
|
+
'pst': 'America/Los_Angeles',
|
|
97
|
+
'toronto': 'America/Toronto',
|
|
98
|
+
'sao_paulo': 'America/Sao_Paulo'
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
def pyread(filename, *, encoding='utf-8', as_list=False, **kwargs):
|
|
102
|
+
match filename:
|
|
103
|
+
case filename if filename.endswith('.txt'):
|
|
104
|
+
with open(filename, 'r', encoding=encoding) as file:
|
|
105
|
+
result=file.read().strip()
|
|
106
|
+
return result if as_list==False else result.split('\n')
|
|
107
|
+
case filename if filename.endswith('.json'):
|
|
108
|
+
with open(filename, 'r', encoding=encoding) as file:
|
|
109
|
+
return json.load(file)
|
|
110
|
+
case filename if filename.endswith('.pickle'):
|
|
111
|
+
with open(filename, 'rb') as file:
|
|
112
|
+
return pickle.load(file)
|
|
113
|
+
case filename if filename.endswith('.csv'):
|
|
114
|
+
return read_csv(filename, encoding=encoding, **kwargs)
|
|
115
|
+
case filename if filename.endswith('.parquet'):
|
|
116
|
+
return read_parquet(filename, **kwargs)
|
|
117
|
+
case filename if filename.endswith('.xlsx'):
|
|
118
|
+
result=read_excel(filename, **kwargs)
|
|
119
|
+
if isinstance(result, dict) and len(result)==1:
|
|
120
|
+
result=[i for i in result.values()]
|
|
121
|
+
result=result[0]
|
|
122
|
+
return result
|
|
123
|
+
case _:
|
|
124
|
+
raise ValueError('Unsupported File!!!')
|
|
125
|
+
|
|
126
|
+
def pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs):
|
|
127
|
+
match filename:
|
|
128
|
+
case filename if filename.endswith('.txt'):
|
|
129
|
+
with open(filename, 'a', encoding=encoding) as file:
|
|
130
|
+
match value:
|
|
131
|
+
case value if type(value) in data_types:
|
|
132
|
+
file.write(value)
|
|
133
|
+
case _:
|
|
134
|
+
file.writelines(value)
|
|
135
|
+
case filename if filename.endswith(('.json', '.pickle')):
|
|
136
|
+
file=pyread(filename, encoding=encoding)
|
|
137
|
+
file=pyupdate(file, value)
|
|
138
|
+
pyrewrite(filename, file)
|
|
139
|
+
case filename if filename.endswith('.csv'):
|
|
140
|
+
kw1={i: j for i, j in kwargs.items() if i in csvread_parameters}
|
|
141
|
+
file=pyread(filename, encoding=encoding, **kw1)
|
|
142
|
+
file=concat([file, value])
|
|
143
|
+
kw2={i: j for i, j in kwargs.items() if i in csvrewrite_parameters}
|
|
144
|
+
pyrewrite(filename, file, **kw2)
|
|
145
|
+
case filename if filename.endswith('.parquet'):
|
|
146
|
+
makedirs(filename, exist_ok=True)
|
|
147
|
+
table=Table.from_pandas(value)
|
|
148
|
+
write_to_dataset(table, root_path=filename, **kwargs)
|
|
149
|
+
case filename if filename.endswith('.xlsx'):
|
|
150
|
+
value=[value] if not isinstance(value, list) else value
|
|
151
|
+
if sheet_name is None:
|
|
152
|
+
c=load_workbook(filename, read_only=True)
|
|
153
|
+
try:
|
|
154
|
+
sheet_name=c.sheetnames
|
|
155
|
+
finally:
|
|
156
|
+
c.close()
|
|
157
|
+
else:
|
|
158
|
+
sheet_name=[sheet_name] if not isinstance(sheet_name, list) else sheet_name
|
|
159
|
+
if len(value)==len(sheet_name):
|
|
160
|
+
kw1={i: j for i, j in kwargs.items() if i in excelread_parameters}
|
|
161
|
+
file=pyread(filename, sheet_name=sheet_name, **kw1)
|
|
162
|
+
df_list=[concat([i, j]) for i, j in zip(file.values(), value)]
|
|
163
|
+
kw2={i: j for i, j in kwargs.items() if i in excelrewrite_parameters}
|
|
164
|
+
pyrewrite(filename, df_list, sheet_name=sheet_name, **kw2)
|
|
165
|
+
else:
|
|
166
|
+
raise ValueError('The number of values should be equal to the number of sheet names!!!')
|
|
167
|
+
case _:
|
|
168
|
+
raise ValueError('Unsupported File!!!')
|
|
169
|
+
|
|
170
|
+
def pyupdate(d1, d2):
|
|
171
|
+
for i in d2:
|
|
172
|
+
if i in d1:
|
|
173
|
+
if isinstance(d1[i], data_structures) and isinstance(d2[i], data_structures):
|
|
174
|
+
d1[i]=d1[i]+d2[i]
|
|
175
|
+
elif isinstance(d1[i], data_structures) and isinstance(d2[i], data_types):
|
|
176
|
+
d1[i].append(d2[i])
|
|
177
|
+
elif isinstance(d1[i], data_types) and isinstance(d2[i], data_structures):
|
|
178
|
+
d1[i]=[d1[i]]
|
|
179
|
+
d1[i].extend(d2[i])
|
|
180
|
+
elif isinstance(d1[i], dict) and isinstance(d2[i], dict):
|
|
181
|
+
pyupdate(d1[i], d2[i])
|
|
182
|
+
else:
|
|
183
|
+
d1[i]=[d1[i], d2[i]]
|
|
184
|
+
else:
|
|
185
|
+
d1[i]=d2[i]
|
|
186
|
+
return d1
|
|
187
|
+
|
|
188
|
+
def pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, head_font='Arial', head_size=12,
|
|
189
|
+
head_font_color='black', head_cell_color='white', font='Arial', size=11, font_color='black',
|
|
190
|
+
cell_color='white', border_color='white', date_format='yyyy-mm-dd',
|
|
191
|
+
time_format='hh:mm:ss', **kwargs):
|
|
192
|
+
match filename:
|
|
193
|
+
case filename if filename.endswith('.txt'):
|
|
194
|
+
with open(filename, 'w', encoding=encoding) as file:
|
|
195
|
+
match value:
|
|
196
|
+
case value if type(value) in data_types:
|
|
197
|
+
file.write(value)
|
|
198
|
+
case _:
|
|
199
|
+
file.writelines(value)
|
|
200
|
+
case filename if filename.endswith('.json'):
|
|
201
|
+
with open(filename, 'w', encoding=encoding) as file:
|
|
202
|
+
json.dump(value, file)
|
|
203
|
+
case filename if filename.endswith('.pickle'):
|
|
204
|
+
with open(filename, 'wb') as file:
|
|
205
|
+
pickle.dump(value, file)
|
|
206
|
+
case filename if filename.endswith('.csv'):
|
|
207
|
+
value.to_csv(filename, encoding=encoding, **kwargs)
|
|
208
|
+
case filename if filename.endswith('.parquet'):
|
|
209
|
+
value.to_parquet(filename, **kwargs)
|
|
210
|
+
case filename if filename.endswith('.xlsx'):
|
|
211
|
+
value=[value] if not isinstance(value, list) else value
|
|
212
|
+
if sheet_name is None:
|
|
213
|
+
if exists(filename):
|
|
214
|
+
c=load_workbook(filename, read_only=True)
|
|
215
|
+
try:
|
|
216
|
+
sheet_name=c.sheetnames
|
|
217
|
+
finally:
|
|
218
|
+
c.close()
|
|
219
|
+
else:
|
|
220
|
+
sheet_name=[f'Sheet{i}' for i in range(1, len(value)+1)]
|
|
221
|
+
else:
|
|
222
|
+
sheet_name=[sheet_name] if not isinstance(sheet_name, list) else sheet_name
|
|
223
|
+
if len(value)==len(sheet_name):
|
|
224
|
+
ex={'mode': 'a', 'if_sheet_exists': 'replace'} if exists(filename) else {'mode': 'w'}
|
|
225
|
+
with ExcelWriter(filename, engine='openpyxl', **ex) as writer:
|
|
226
|
+
for i, j in zip(value, sheet_name):
|
|
227
|
+
i.to_excel(writer, sheet_name=j, index=False, **kwargs)
|
|
228
|
+
worksheet=writer.sheets[j]
|
|
229
|
+
header_font=Font(name=head_font, size=head_size, bold=True, color=colors[head_font_color])
|
|
230
|
+
header_fill=PatternFill(start_color=colors[head_cell_color],
|
|
231
|
+
end_color=colors[head_cell_color], fill_type='solid')
|
|
232
|
+
data_font=Font(name=font, size=size, color=colors[font_color])
|
|
233
|
+
data_fill=PatternFill(start_color=colors[cell_color],
|
|
234
|
+
end_color=colors[cell_color], fill_type='solid')
|
|
235
|
+
thin_side=Side(border_style='thin', color=colors[border_color])
|
|
236
|
+
border=Border(left=thin_side, right=thin_side, top=thin_side, bottom=thin_side)
|
|
237
|
+
center_alignment=Alignment(horizontal='center', vertical='center')
|
|
238
|
+
for col_idx in range(1, len(i.columns)+1):
|
|
239
|
+
cell=worksheet.cell(row=1, column=col_idx)
|
|
240
|
+
cell.font=header_font
|
|
241
|
+
cell.fill=header_fill
|
|
242
|
+
cell.alignment=center_alignment
|
|
243
|
+
cell.border=border
|
|
244
|
+
for row in range(2, len(i)+2):
|
|
245
|
+
for col in range(1, len(i.columns)+1):
|
|
246
|
+
cell=worksheet.cell(row=row, column=col)
|
|
247
|
+
cell.font=data_font
|
|
248
|
+
cell.fill=data_fill
|
|
249
|
+
cell.border=border
|
|
250
|
+
col_name=i.columns[col-1]
|
|
251
|
+
value_type=i[col_name].dtype
|
|
252
|
+
if str(value_type) in type_formats:
|
|
253
|
+
config=type_formats[str(value_type)]
|
|
254
|
+
elif str(value_type)=='datetime64[ns]':
|
|
255
|
+
valid_series=i[col_name].dropna()
|
|
256
|
+
first_value=valid_series[0] if not valid_series.empty else None
|
|
257
|
+
if first_value is not None:
|
|
258
|
+
date_list=[str(i.date()) for i in valid_series]
|
|
259
|
+
time_list=[str(i.time()) for i in valid_series]
|
|
260
|
+
if all(i==time_list[0] for i in time_list):
|
|
261
|
+
type_formats['datetime64[ns]']=date_format
|
|
262
|
+
elif all(i==date_list[0] for i in date_list):
|
|
263
|
+
type_formats['datetime64[ns]']=time_format
|
|
264
|
+
else:
|
|
265
|
+
type_formats['datetime64[ns]']=f'{date_format} {time_format}'
|
|
266
|
+
else:
|
|
267
|
+
type_formats['datetime64[ns]']='General'
|
|
268
|
+
config=type_formats['datetime64[ns]']
|
|
269
|
+
elif issubdtype(value_type, integer):
|
|
270
|
+
config=type_formats['integer']
|
|
271
|
+
elif issubdtype(value_type, floating):
|
|
272
|
+
config=type_formats['float']
|
|
273
|
+
else:
|
|
274
|
+
config=type_formats['default']
|
|
275
|
+
cell.number_format=config
|
|
276
|
+
for col in worksheet.columns:
|
|
277
|
+
max_len=max(len(str(cell.value or '')) for cell in col)
|
|
278
|
+
header_len=len(str(col[0].value or ''))
|
|
279
|
+
col_letter=col[0].column_letter
|
|
280
|
+
worksheet.column_dimensions[col_letter].width=max(max_len, header_len)+5
|
|
281
|
+
else:
|
|
282
|
+
raise ValueError('The number of values should be equal to the number of sheet names!!!')
|
|
283
|
+
case _:
|
|
284
|
+
raise ValueError('Unsupported File!!!')
|
|
285
|
+
|
|
286
|
+
pyread_parameters=[i for i in signature(pyread).parameters]
|
|
287
|
+
pyrewrite_parameters=[i for i in signature(pyrewrite).parameters]
|
|
288
|
+
excelrewrite_parameters=[i for i in signature(DataFrame.to_excel).parameters]+pyrewrite_parameters
|
|
289
|
+
excelrewrite_parameters.remove('kwargs')
|
|
290
|
+
|
|
291
|
+
def super_round(value, num=0):
|
|
292
|
+
if '.' not in str(value):
|
|
293
|
+
value=float(f'{value}.0')
|
|
294
|
+
n1=1 if value>=0 else -1
|
|
295
|
+
a, b=str(f"{abs(value)}").split('.')
|
|
296
|
+
if b=='0':
|
|
297
|
+
return int(a)
|
|
298
|
+
if len(b)<num+1:
|
|
299
|
+
b=b.ljust(len(b)+(num+1-len(b)), '0')
|
|
300
|
+
elif len(b)>num+1:
|
|
301
|
+
b=b[:num+1]
|
|
302
|
+
b_list=list(b[::-1])
|
|
303
|
+
if b_list[0] in ['5', '6', '7', '8', '9']:
|
|
304
|
+
n2=1
|
|
305
|
+
for i in range(1, len(b_list)):
|
|
306
|
+
b_list[i]=str(int(b_list[i])+n2)
|
|
307
|
+
if b_list[i]=='10':
|
|
308
|
+
b_list[i]='0'
|
|
309
|
+
n2=1
|
|
310
|
+
else:
|
|
311
|
+
n2=0
|
|
312
|
+
break
|
|
313
|
+
else:
|
|
314
|
+
n2=0
|
|
315
|
+
b_list[0]='0'
|
|
316
|
+
b_list=reversed(b_list)
|
|
317
|
+
result=f'{n2+int(a)}.{''.join(b_list)}'
|
|
318
|
+
return n1*float(result)
|
|
319
|
+
|
|
320
|
+
def root(number, base=2, precision=2):
|
|
321
|
+
if base<2:
|
|
322
|
+
raise ValueError("The degree of the root must be greater than or equal to 2!!!")
|
|
323
|
+
if number<0 and base%2==0:
|
|
324
|
+
raise ValueError("You can't extract the root of an even power from a negative number!!!")
|
|
325
|
+
else:
|
|
326
|
+
n=1 if number>=0 else -1
|
|
327
|
+
result=abs(number)**(1/base)
|
|
328
|
+
return super_round(n*result, precision)
|
|
329
|
+
|
|
330
|
+
def quadratic_equation(a, b=0, c=0):
|
|
331
|
+
if a==0:
|
|
332
|
+
if b==0:
|
|
333
|
+
return None
|
|
334
|
+
return -c/b
|
|
335
|
+
d=b**2-(4*a*c)
|
|
336
|
+
if d<0:
|
|
337
|
+
return None
|
|
338
|
+
elif d==0:
|
|
339
|
+
return -b/(2*a)
|
|
340
|
+
else:
|
|
341
|
+
x1=((-b)+root(d))/(2*a)
|
|
342
|
+
x2=((-b)-root(d))/(2*a)
|
|
343
|
+
return (x1, x2)
|
|
344
|
+
|
|
345
|
+
def onelist(lst):
|
|
346
|
+
result=[]
|
|
347
|
+
for i in lst:
|
|
348
|
+
if isinstance(i, data_structures):
|
|
349
|
+
result.extend(onelist(i))
|
|
350
|
+
else:
|
|
351
|
+
result.append(i)
|
|
352
|
+
return result
|
|
353
|
+
|
|
354
|
+
def make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres'):
|
|
355
|
+
match db_type.lower():
|
|
356
|
+
case 'postgresql' | 'postgres':
|
|
357
|
+
db_path=f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
|
|
358
|
+
case 'mysql':
|
|
359
|
+
db_path=f"mysql+pymysql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
|
|
360
|
+
case 'sqlite':
|
|
361
|
+
db_path=f"sqlite:///{db_name}"
|
|
362
|
+
case _:
|
|
363
|
+
raise ValueError("Unsupported database type!!!")
|
|
364
|
+
return create_engine(db_path)
|
|
365
|
+
|
|
366
|
+
def sqlread(query, db_name, *, db_user=None, db_password=None, db_host='localhost',
|
|
367
|
+
db_port=5432, db_type='postgres', **kwargs):
|
|
368
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
369
|
+
result=read_sql(query, con=engine, **kwargs)
|
|
370
|
+
return result
|
|
371
|
+
|
|
372
|
+
def sqlrewrite(table_name, new_value, db_name, *, db_user=None, db_password=None,
|
|
373
|
+
db_host='localhost', db_port=5432, db_type='postgres', chunksize=50000, **kwargs):
|
|
374
|
+
kwargs.pop('if_exists', None)
|
|
375
|
+
kwargs.pop('method', None)
|
|
376
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
377
|
+
for n, i in enumerate(range(0, len(new_value), chunksize)):
|
|
378
|
+
chunk=new_value.iloc[i:i+chunksize]
|
|
379
|
+
mode="replace" if n==0 else "append"
|
|
380
|
+
chunk.to_sql(table_name, con=engine, if_exists=mode, index=False, method='multi', **kwargs)
|
|
381
|
+
|
|
382
|
+
sqlread_parameters=[i for i in signature(sqlread).parameters]
|
|
383
|
+
sqlrewrite_parameters=[i for i in signature(sqlrewrite).parameters]
|
|
384
|
+
|
|
385
|
+
def sqladd(table_name, new_value, db_name, *, db_user=None, db_password=None,
|
|
386
|
+
db_host='localhost', db_port=5432, db_type='postgres', chunksize=50000, **kwargs):
|
|
387
|
+
kwargs.pop('if_exists', None)
|
|
388
|
+
kwargs.pop('method', None)
|
|
389
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
390
|
+
for i in range(0, len(new_value), chunksize):
|
|
391
|
+
chunk=new_value.iloc[i:i+chunksize]
|
|
392
|
+
chunk.to_sql(table_name, con=engine, if_exists="append", index=False, method='multi', **kwargs)
|
|
393
|
+
|
|
394
|
+
def transform_from_sql(filepath, query, db_name, **kwargs):
|
|
395
|
+
match filepath:
|
|
396
|
+
case filepath if filepath.endswith('.csv'):
|
|
397
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_csv).parameters]
|
|
398
|
+
case filepath if filepath.endswith('.parquet'):
|
|
399
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_parquet).parameters]
|
|
400
|
+
case filepath if filepath.endswith('.xlsx'):
|
|
401
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_excel).parameters]+pyrewrite_parameters
|
|
402
|
+
case _:
|
|
403
|
+
raise ValueError('Unsupported file!!!')
|
|
404
|
+
k1={i: j for i, j in kwargs.items() if i in sqlread_parameters}
|
|
405
|
+
result=sqlread(query, db_name, **k1)
|
|
406
|
+
k2={i: j for i, j in kwargs.items() if i in from_sql_parameters}
|
|
407
|
+
pyrewrite(filepath, result, **k2)
|
|
408
|
+
|
|
409
|
+
def transform_to_sql(filepath, table_name, db_name, **kwargs):
|
|
410
|
+
match filepath:
|
|
411
|
+
case filepath if filepath.endswith('.csv'):
|
|
412
|
+
to_sql_parameters=[i for i in signature(read_csv).parameters]
|
|
413
|
+
case filepath if filepath.endswith('.parquet'):
|
|
414
|
+
to_sql_parameters=[i for i in signature(read_parquet).parameters]
|
|
415
|
+
case filepath if filepath.endswith('.xlsx'):
|
|
416
|
+
to_sql_parameters=[i for i in signature(read_excel).parameters]+pyread_parameters
|
|
417
|
+
case _:
|
|
418
|
+
raise ValueError('Unsupported file!!!')
|
|
419
|
+
k1={i: j for i, j in kwargs.items() if i in to_sql_parameters}
|
|
420
|
+
result=pyread(filepath, **k1)
|
|
421
|
+
k2={i: j for i, j in kwargs.items() if i in sqlrewrite_parameters}
|
|
422
|
+
sqlrewrite(table_name, result, db_name, **k2)
|
|
423
|
+
|
|
424
|
+
def take_month(value):
|
|
425
|
+
if value in ('january', 'jan', 'январь', 'января', 'янв', '01', '1'):
|
|
426
|
+
return [1, 31]
|
|
427
|
+
elif value in ('february', 'feb', 'февраль', 'февраля', 'фев', '02', '2'):
|
|
428
|
+
return [2, 28]
|
|
429
|
+
elif value in ('march', 'mar', 'март', 'марта', 'мар', '03', '3'):
|
|
430
|
+
return [3, 31]
|
|
431
|
+
elif value in ('april', 'apr', 'апрель', 'апреля', 'апр', '04', '4'):
|
|
432
|
+
return [4, 30]
|
|
433
|
+
elif value in ('may', 'май', 'мая', '05', '5'):
|
|
434
|
+
return [5, 31]
|
|
435
|
+
elif value in ('june', 'jun', 'июнь', 'июня', 'июн', '06', '6'):
|
|
436
|
+
return [6, 30]
|
|
437
|
+
elif value in ('july', 'jul', 'июль', 'июля', 'июл', '07', '7'):
|
|
438
|
+
return [7, 31]
|
|
439
|
+
elif value in ('august', 'aug', 'август', 'августа', 'авг', '08', '8'):
|
|
440
|
+
return [8, 31]
|
|
441
|
+
elif value in ('september', 'sep', 'сентябрь', 'сентября', 'сен', '09', '9'):
|
|
442
|
+
return [9, 30]
|
|
443
|
+
elif value in ('october', 'oct', 'октябрь', 'октября', 'окт', '10'):
|
|
444
|
+
return [10, 31]
|
|
445
|
+
elif value in ('november', 'nov', 'ноябрь', 'ноября', 'ноя', '11'):
|
|
446
|
+
return [11, 30]
|
|
447
|
+
elif value in ('december', 'dec', 'декабрь', 'декабря', 'дек', '12'):
|
|
448
|
+
return [12, 31]
|
|
449
|
+
else:
|
|
450
|
+
raise ValueError('The entered month does not exist!!!')
|
|
451
|
+
|
|
452
|
+
def take_weekday(value, start_zero, start_sunday):
|
|
453
|
+
numweek_list=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12',
|
|
454
|
+
'01', '02', '03', '04', '05', '06', '07', '08', '09']
|
|
455
|
+
if value.startswith(('monday', 'mon', 'mo', 'понедельник', 'пон', 'пн', '01', '1')):
|
|
456
|
+
result=1
|
|
457
|
+
elif value.startswith(('tuesday', 'tue', 'tu', 'вторник', 'вто', 'вт', '02', '2')):
|
|
458
|
+
result=2
|
|
459
|
+
elif value.startswith(('wednesday', 'wed', 'we', 'среда', 'сре', 'ср', '03', '3')):
|
|
460
|
+
result=3
|
|
461
|
+
elif value.startswith(('thursday', 'thu', 'th', 'четверг', 'чет', 'чт', '04', '4')):
|
|
462
|
+
result=4
|
|
463
|
+
elif value.startswith(('friday', 'fri', 'fr', 'пятница', 'пят', 'пт', '05', '5')):
|
|
464
|
+
result=5
|
|
465
|
+
elif value.startswith(('saturday', 'sat', 'sa', 'суббота', 'суб', 'сб', '06', '6')):
|
|
466
|
+
result=6
|
|
467
|
+
elif value.startswith(('sunday', 'sun', 'su', 'воскресенье', 'вос', 'вс', '07', '7')):
|
|
468
|
+
result=7
|
|
469
|
+
else:
|
|
470
|
+
raise ValueError('The entered day of the week does not exist!!!')
|
|
471
|
+
if start_zero==True and value in numweek_list:
|
|
472
|
+
result+=1
|
|
473
|
+
if start_sunday==True:
|
|
474
|
+
result-=1
|
|
475
|
+
if result==0:
|
|
476
|
+
result=7
|
|
477
|
+
return result
|
|
478
|
+
|
|
479
|
+
def distributor(s):
|
|
480
|
+
s=[i for i in s if i!=' ']
|
|
481
|
+
result=[]
|
|
482
|
+
elem=[]
|
|
483
|
+
isnum=True
|
|
484
|
+
for i in s:
|
|
485
|
+
if i.isdigit() and isnum==True:
|
|
486
|
+
elem.append(i)
|
|
487
|
+
elif (i.isalpha() or i==',') and isnum==False:
|
|
488
|
+
elem.append(i)
|
|
489
|
+
else:
|
|
490
|
+
ready_elem=''.join(elem)
|
|
491
|
+
if ready_elem.endswith('and'):
|
|
492
|
+
ready_elem=ready_elem[:-3]
|
|
493
|
+
elif ready_elem.endswith(',') or ready_elem.endswith('и'):
|
|
494
|
+
ready_elem=ready_elem[:-1]
|
|
495
|
+
result.append(ready_elem)
|
|
496
|
+
elem=[i]
|
|
497
|
+
isnum=not isnum
|
|
498
|
+
result.append(''.join(elem))
|
|
499
|
+
result=[i.strip() for i in result if i!='']
|
|
500
|
+
return result
|
|
501
|
+
|
|
502
|
+
def work_timezone1(value, to_tz, from_tz):
|
|
503
|
+
if to_tz in timezones:
|
|
504
|
+
if from_tz is None:
|
|
505
|
+
from_tz=datetime.now().astimezone().tzinfo
|
|
506
|
+
else:
|
|
507
|
+
from_tz=timezones[from_tz.lower()]
|
|
508
|
+
to_tz=timezones[to_tz.lower()]
|
|
509
|
+
value=value.tz_localize(from_tz).tz_convert(to_tz)
|
|
510
|
+
elif from_tz in timezones:
|
|
511
|
+
from_tz=timezones[from_tz.lower()]
|
|
512
|
+
value=value.tz_localize(from_tz)
|
|
513
|
+
return value
|
|
514
|
+
|
|
515
|
+
def work_timezone2(value, keyword, to_tz, from_tz):
|
|
516
|
+
if to_tz not in timezones and from_tz not in timezones:
|
|
517
|
+
return value.strftime('%X') if keyword=='time' else value.strftime('%Y-%m-%d %X')
|
|
518
|
+
value=value.strftime('%X %z') if keyword=='time' else value.strftime('%Y-%m-%d %X %z')
|
|
519
|
+
value=list(value)
|
|
520
|
+
value.insert(-2, ':')
|
|
521
|
+
value=''.join(value)
|
|
522
|
+
return value.strip()
|
|
523
|
+
|
|
524
|
+
dt_list={'yesterday', 'the day before yesterday', 'tomorrow', 'the day after tomorrow', 'today', 'now', 'ago',
|
|
525
|
+
'in', 'half an hour ago', 'in half an hour', 'an hour and a half ago', 'in an hour and a half', 'next',
|
|
526
|
+
'last', 'this', 'вчера', 'позавчера', 'завтра', 'послезавтра', 'сегодня', 'сейчас', 'назад', 'через',
|
|
527
|
+
'полчаса назад', 'через полчаса', 'полтора часа назад', 'через полтора часа', 'следующ', 'прошл',
|
|
528
|
+
'предыдущ', 'эт'}
|
|
529
|
+
|
|
530
|
+
def relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now',
|
|
531
|
+
from_tz=None, to_tz=None):
|
|
532
|
+
value=value.lower()
|
|
533
|
+
if keyword=='date':
|
|
534
|
+
current=Timestamp(current_date)
|
|
535
|
+
elif keyword=='time':
|
|
536
|
+
current=work_timezone1(Timestamp(current_time), to_tz, from_tz)
|
|
537
|
+
else:
|
|
538
|
+
current=work_timezone1(Timestamp(current_datetime), to_tz, from_tz)
|
|
539
|
+
if value in ('yesterday', 'вчера'):
|
|
540
|
+
result=current-DateOffset(days=1)
|
|
541
|
+
elif value in ('the day before yesterday', 'позавчера'):
|
|
542
|
+
result=current-DateOffset(days=2)
|
|
543
|
+
elif value in ('tomorrow', 'завтра'):
|
|
544
|
+
result=current+DateOffset(days=1)
|
|
545
|
+
elif value in ('the day after tomorrow', 'послезавтра'):
|
|
546
|
+
result=current+DateOffset(days=2)
|
|
547
|
+
elif value in ('today', 'now', 'сегодня', 'сейчас'):
|
|
548
|
+
result=current
|
|
549
|
+
elif value in ('half an hour ago', 'полчаса назад'):
|
|
550
|
+
result=current-DateOffset(minutes=30)
|
|
551
|
+
elif value in ('an hour and a half ago', 'полтора часа назад'):
|
|
552
|
+
result=current-DateOffset(minutes=90)
|
|
553
|
+
elif value in ('in half an hour', 'через полчаса'):
|
|
554
|
+
result=current+DateOffset(minutes=30)
|
|
555
|
+
elif value in ('in an hour and a half', 'через полтора часа'):
|
|
556
|
+
result=current+DateOffset(minutes=90)
|
|
557
|
+
else:
|
|
558
|
+
value=value.split()
|
|
559
|
+
value=[i for i in value if i not in {'в', 'на', 'к', 'со'}]
|
|
560
|
+
if value[0].startswith(('next', 'следующ')):
|
|
561
|
+
if value[-1].startswith(('year', 'год')):
|
|
562
|
+
result=current+DateOffset(years=1)
|
|
563
|
+
elif value[-1].startswith(('month', 'месяц')):
|
|
564
|
+
result=current+DateOffset(months=1)
|
|
565
|
+
elif value[-1].startswith(('week', 'недел')):
|
|
566
|
+
result=current+DateOffset(weeks=1)
|
|
567
|
+
else:
|
|
568
|
+
current_day=current.dayofweek+1
|
|
569
|
+
next_day=take_weekday(value[-1], False, False)
|
|
570
|
+
result=current+DateOffset(days=7+(next_day-current_day))
|
|
571
|
+
elif value[0].startswith(('last', 'прошл', 'предыдущ')):
|
|
572
|
+
if value[-1].startswith(('year', 'год')):
|
|
573
|
+
result=current-DateOffset(years=1)
|
|
574
|
+
elif value[-1].startswith(('month', 'месяц')):
|
|
575
|
+
result=current-DateOffset(months=1)
|
|
576
|
+
elif value[-1].startswith(('week', 'недел')):
|
|
577
|
+
result=current-DateOffset(weeks=1)
|
|
578
|
+
else:
|
|
579
|
+
current_day=current.dayofweek+1
|
|
580
|
+
next_day=take_weekday(value[-1], False, False)
|
|
581
|
+
result=current-DateOffset(days=7-(next_day-current_day))
|
|
582
|
+
elif value[0].startswith(('this', 'эт')):
|
|
583
|
+
if value[-1].startswith(('year', 'month', 'week', 'год', 'месяц', 'недел')):
|
|
584
|
+
result=current
|
|
585
|
+
else:
|
|
586
|
+
current_day=current.dayofweek+1
|
|
587
|
+
next_day=take_weekday(value[-1], False, False)
|
|
588
|
+
result=current-DateOffset(days=current_day-next_day)
|
|
589
|
+
else:
|
|
590
|
+
if value[-1] in ('ago', 'назад'):
|
|
591
|
+
if value[0] in ('a', 'an'):
|
|
592
|
+
value[0]='1'
|
|
593
|
+
elif len(value)==2:
|
|
594
|
+
value.insert(0, '1')
|
|
595
|
+
word=''.join(value[:-1])
|
|
596
|
+
else:
|
|
597
|
+
if value[1] in ('a', 'an'):
|
|
598
|
+
value[1]='1'
|
|
599
|
+
elif len(value)==2:
|
|
600
|
+
value.insert(1, '1')
|
|
601
|
+
word=''.join(value[1:])
|
|
602
|
+
years, weeks, months, days, hours, minutes, seconds=0, 0, 0, 0, 0, 0, 0
|
|
603
|
+
distrub_list=distributor(word)
|
|
604
|
+
for i in range(0, len(distrub_list), 2):
|
|
605
|
+
if any(x==distrub_list[i+1] for x in ['day', 'days', 'день', 'дня', 'дней']):
|
|
606
|
+
days+=int(distrub_list[i])
|
|
607
|
+
if any(x==distrub_list[i+1] for x in ['week', 'weeks', 'неделю', 'недель', 'недели']):
|
|
608
|
+
weeks+=int(distrub_list[i])
|
|
609
|
+
if any(x==distrub_list[i+1] for x in ['month', 'months', 'месяц', 'месяца', 'месяцев']):
|
|
610
|
+
months+=int(distrub_list[i])
|
|
611
|
+
if any(x==distrub_list[i+1] for x in ['year', 'years', 'год', 'года', 'лет']):
|
|
612
|
+
years+=int(distrub_list[i])
|
|
613
|
+
if any(x==distrub_list[i+1] for x in ['h', 'hour', 'hours', 'ч', 'час', 'часа', 'часов']):
|
|
614
|
+
hours+=int(distrub_list[i])
|
|
615
|
+
if any(x==distrub_list[i+1] for x in ['m', 'min', 'minute', 'minutes', 'м', 'мин', 'минут', 'минуту']):
|
|
616
|
+
minutes+=int(distrub_list[i])
|
|
617
|
+
if any(x==distrub_list[i+1] for x in ['s', 'sec', 'second', 'seconds', 'с', 'сек', 'секунд', 'секунду']):
|
|
618
|
+
seconds+=int(distrub_list[i])
|
|
619
|
+
offset=DateOffset(years=years, weeks=weeks, months=months, days=days,
|
|
620
|
+
hours=hours, minutes=minutes, seconds=seconds)
|
|
621
|
+
if value[-1] in ('ago', 'назад'):
|
|
622
|
+
result=current-offset
|
|
623
|
+
elif value[0] in ('in', 'через'):
|
|
624
|
+
result=current+offset
|
|
625
|
+
if keyword=='date':
|
|
626
|
+
return result.strftime('%Y-%m-%d')
|
|
627
|
+
return work_timezone2(result, keyword, to_tz, from_tz)
|
|
628
|
+
|
|
629
|
+
def make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False):
|
|
630
|
+
if isinstance(value, str):
|
|
631
|
+
keyword='date'
|
|
632
|
+
value=value.lower().strip()
|
|
633
|
+
if any(i in value for i in dt_list):
|
|
634
|
+
return relative_datetime(value, keyword, current_date=current_date)
|
|
635
|
+
lst=re.split(r'[-/.,: ]', value)
|
|
636
|
+
lst=[i.strip() for i in lst if i!='']
|
|
637
|
+
else:
|
|
638
|
+
lst=value
|
|
639
|
+
lst=lst[:len(order)]
|
|
640
|
+
if 'y' not in order:
|
|
641
|
+
current_year=Timestamp(current_date).year
|
|
642
|
+
lst.append(str(current_year))
|
|
643
|
+
year_idx=2
|
|
644
|
+
else:
|
|
645
|
+
year_idx=order.index('y')
|
|
646
|
+
if len(lst[year_idx])==2:
|
|
647
|
+
lst[year_idx]=f'{str(century-1)}{lst[year_idx]}'
|
|
648
|
+
elif len(lst[year_idx])<2:
|
|
649
|
+
raise ValueError('The year should not be less than 100!!!')
|
|
650
|
+
if 'n' in order and 'w' in order:
|
|
651
|
+
numweek_idx=order.index('n')
|
|
652
|
+
weekday_idx=order.index('w')
|
|
653
|
+
weekday_value=take_weekday(lst[weekday_idx], start_zero, start_sunday)
|
|
654
|
+
if lst[numweek_idx].startswith('w'):
|
|
655
|
+
lst[numweek_idx]=lst[numweek_idx][1:]
|
|
656
|
+
first_day_year=str(Timestamp(lst[year_idx]).dayofweek+1)
|
|
657
|
+
if (int(lst[year_idx])%4==0 and first_day_year in ('3', '4')) or first_day_year=='4':
|
|
658
|
+
max_numweek=53
|
|
659
|
+
else:
|
|
660
|
+
max_numweek=52
|
|
661
|
+
if 0<int(lst[numweek_idx])<=max_numweek:
|
|
662
|
+
result=f'{lst[year_idx]}-W{lst[numweek_idx]}-{weekday_value}'
|
|
663
|
+
return str(to_datetime(result, format='%G-W%V-%u').date())
|
|
664
|
+
raise ValueError('The week number must not exceed the maximum number of the specified year!!!')
|
|
665
|
+
else:
|
|
666
|
+
month_idx=order.index('m')
|
|
667
|
+
day_idx=order.index('d')
|
|
668
|
+
month_values=take_month(lst[month_idx].lower())
|
|
669
|
+
if int(lst[year_idx])%4==0 and month_values[0]==2:
|
|
670
|
+
month_values[1]+=1
|
|
671
|
+
lst[month_idx]=month_values[0]
|
|
672
|
+
if 0<int(lst[day_idx])<=month_values[1]:
|
|
673
|
+
return f'{lst[year_idx]}-{str(lst[month_idx]).zfill(2)}-{str(lst[day_idx]).zfill(2)}'
|
|
674
|
+
raise ValueError('A month cannot be more than 12!!!')
|
|
675
|
+
|
|
676
|
+
def make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None):
|
|
677
|
+
keyword='time'
|
|
678
|
+
if isinstance(value, str):
|
|
679
|
+
value=value.lower()
|
|
680
|
+
if any(i in value for i in dt_list):
|
|
681
|
+
return relative_datetime(value, keyword, current_time=current_time, from_tz=from_tz, to_tz=to_tz)
|
|
682
|
+
pattern=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])\s*|\s*[-/.,: ]\s*'
|
|
683
|
+
lst=re.split(pattern, value)
|
|
684
|
+
lst=[i.strip() for i in lst if i!='']
|
|
685
|
+
else:
|
|
686
|
+
lst=value.copy()
|
|
687
|
+
lst=[i.strip() for i in lst if i.strip() not in ['am', 'pm', 'a.m', 'p.m']]
|
|
688
|
+
order=order[:len(lst)]
|
|
689
|
+
if not any(i in {'H', 'M', 'S'} for i in order):
|
|
690
|
+
raise ValueError('Error!!!')
|
|
691
|
+
if 'H' not in order:
|
|
692
|
+
hour_value='00'
|
|
693
|
+
else:
|
|
694
|
+
hour_idx=order.index('H')
|
|
695
|
+
if 'pm' in value or 'p.m.' in value:
|
|
696
|
+
if lst[hour_idx]=='12':
|
|
697
|
+
lst[hour_idx]='12'
|
|
698
|
+
elif 0<=int(lst[hour_idx])<12:
|
|
699
|
+
lst[hour_idx]=str(int(lst[hour_idx].strip())+12)
|
|
700
|
+
if 'am' in value or 'a.m.' in value:
|
|
701
|
+
if lst[hour_idx]=='12':
|
|
702
|
+
lst[hour_idx]='00'
|
|
703
|
+
elif 12<int(lst[hour_idx])<=24:
|
|
704
|
+
lst[hour_idx]=str(int(lst[hour_idx].strip())-12)
|
|
705
|
+
if 0<=int(lst[hour_idx])<24:
|
|
706
|
+
hour_value=lst[hour_idx]
|
|
707
|
+
elif int(lst[hour_idx])==24:
|
|
708
|
+
hour_value='00'
|
|
709
|
+
else:
|
|
710
|
+
raise ValueError('Hours cannot be greater than 24 and less than 0!!!')
|
|
711
|
+
if 'M' not in order:
|
|
712
|
+
minute_value='00'
|
|
713
|
+
else:
|
|
714
|
+
minute_idx=order.index('M')
|
|
715
|
+
if 0<=int(lst[minute_idx])<60:
|
|
716
|
+
minute_value=lst[minute_idx]
|
|
717
|
+
elif int(lst[minute_idx])==60:
|
|
718
|
+
minute_value='00'
|
|
719
|
+
else:
|
|
720
|
+
raise ValueError('Minutes cannot be more than 60 and less than 0!!!')
|
|
721
|
+
if 'S' not in order:
|
|
722
|
+
second_value='00'
|
|
723
|
+
else:
|
|
724
|
+
second_idx=order.index('S')
|
|
725
|
+
if 0<=int(lst[second_idx])<60:
|
|
726
|
+
second_value=lst[second_idx]
|
|
727
|
+
elif int(lst[second_idx])==60:
|
|
728
|
+
second_value='00'
|
|
729
|
+
else:
|
|
730
|
+
raise ValueError('Seconds cannot be greater than 60 and less than 0!!!')
|
|
731
|
+
result=f'{hour_value.zfill(2)}:{minute_value.zfill(2)}:{second_value.zfill(2)}'
|
|
732
|
+
result=work_timezone1(Timestamp(result), to_tz, from_tz)
|
|
733
|
+
return work_timezone2(result, keyword, to_tz, from_tz)
|
|
734
|
+
|
|
735
|
+
def make_datetime(value, *, order_date='ymd', order_time='HMS', century=21, isfirsttime=False,
|
|
736
|
+
start_sunday=False, start_zero=False, current_datetime='now', from_tz=None, to_tz=None):
|
|
737
|
+
value=value.lower().strip()
|
|
738
|
+
if any(i in value for i in dt_list):
|
|
739
|
+
return relative_datetime(value, 'datetime', current_datetime=current_datetime, from_tz=from_tz, to_tz=to_tz)
|
|
740
|
+
pattern1=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])\s*|\s*[-/.,: ]\s*'
|
|
741
|
+
pattern2=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])'
|
|
742
|
+
lst=re.split(pattern1, value)
|
|
743
|
+
lst=[i.strip() for i in lst if i!='']
|
|
744
|
+
special_symbol=re.findall(pattern2, value)[:1]
|
|
745
|
+
special_symbol=''.join(special_symbol).strip()
|
|
746
|
+
part1, part2='', ''
|
|
747
|
+
if isfirsttime is False:
|
|
748
|
+
part1=make_date(lst[:len(order_date)], order=order_date, century=century, start_sunday=start_sunday, start_zero=start_zero)
|
|
749
|
+
if lst[len(order_date):]!=[]:
|
|
750
|
+
part2=make_time(lst[len(order_date):]+[special_symbol], order=order_time)
|
|
751
|
+
else:
|
|
752
|
+
if lst[len(order_time):]!=[]:
|
|
753
|
+
part1=make_date(lst[len(order_time):], order=order_date, century=century, start_sunday=start_sunday, start_zero=start_zero)
|
|
754
|
+
part2=make_time(lst[:len(order_time)]+[special_symbol], order=order_time)
|
|
755
|
+
result=f'{part1} {part2}'.strip()
|
|
756
|
+
result=work_timezone1(Timestamp(result), to_tz, from_tz)
|
|
757
|
+
return work_timezone2(result, 'datetime', to_tz, from_tz)
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: UltraPython
|
|
3
|
+
Version: 1.8.5
|
|
4
|
+
Summary: UltraPython: Utilities of Files, Databases, and Math
|
|
5
|
+
Project-URL: Homepage, https://github.com
|
|
6
|
+
Author: Abdyrahym Begenjov
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2026 Abdyrahym Begenjov
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Requires-Dist: numpy
|
|
31
|
+
Requires-Dist: openpyxl
|
|
32
|
+
Requires-Dist: pandas
|
|
33
|
+
Requires-Dist: pyarrow
|
|
34
|
+
Requires-Dist: sqlalchemy
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# ultrapython-module
|
|
38
|
+
## English
|
|
39
|
+
## UltraPython: Utilities of Files, Databases, and Math 🐍
|
|
40
|
+
UltraPython is a simple and helpful Python library. It helps you work with different files, connect to databases, and do math operations without writing long code. It is great for automating your daily programming tasks.
|
|
41
|
+
> **Note:** This library requires Python 3.10+ because it uses the modern match-case feature.
|
|
42
|
+
|
|
43
|
+
## Key Features
|
|
44
|
+
* **All-in-One File Tools:** Read, write, and append `.txt`, `.json`, `.pickle`, `.csv`, `.parquet`, and `.xlsx` (Excel) files easily.
|
|
45
|
+
* **Smart Excel Styles:** Automatically makes Excel columns wide enough for your data and adds nice colors and fonts.
|
|
46
|
+
* **Simple SQL Database Tools:** Connect to PostgreSQL, MySQL, or SQLite, and move data between files and databases quickly.
|
|
47
|
+
* **Better Math:** Easy functions for math rounding, finding roots, and solving equations.
|
|
48
|
+
|
|
49
|
+
## API Reference & Function Capabilities
|
|
50
|
+
|
|
51
|
+
### `pyread(filename, *, encoding='utf-8', as_list=False, **kwargs)`
|
|
52
|
+
* **Description:** Reads data from a file. It automatically knows the format by looking at the file extension.
|
|
53
|
+
* **Capabilities:**
|
|
54
|
+
* Automatically handles 6 formats: `.txt`, `.json`, `.pickle`, `.csv`, `.parquet`, and `.xlsx`.
|
|
55
|
+
* If you read a `.txt` file with `as_list=True`, it automatically splits the text into a clean list of lines.
|
|
56
|
+
* If you read an Excel file with only one sheet, it automatically extracts it as a single DataFrame instead of a dictionary.
|
|
57
|
+
* Passes extra options (`**kwargs`) directly to internal readers like `pandas.read_csv` or `pandas.read_excel`.
|
|
58
|
+
|
|
59
|
+
### `pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, ...)`
|
|
60
|
+
* **Description:** Clears the target file and writes completely new data into it.
|
|
61
|
+
* **Capabilities:**
|
|
62
|
+
* Supports writing strings and lists to `.txt`, dictionaries to `.json`/`.pickle`, and dataframes to `.csv`/`.parquet`/`.xlsx`.
|
|
63
|
+
* For Excel (`.xlsx`), it automatically designs your table: adds bold headers, custom colors, fonts, and clean thin borders.
|
|
64
|
+
* Automatically auto-fits the Excel column widths based on the longest text in each column.
|
|
65
|
+
* Automatically sets cell data formats in Excel (detects categories, integers, floats, dates, and times).
|
|
66
|
+
|
|
67
|
+
### `pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs)`
|
|
68
|
+
* **Description:** Adds new data to the end of an existing file without deleting the old content.
|
|
69
|
+
* **Capabilities:**
|
|
70
|
+
* For `.txt` files, it appends new text lines directly to the end.
|
|
71
|
+
* For `.json` and `.pickle`, it reads the old data first, merges it safely with the new data using `pyupdate`, and overwrites the file.
|
|
72
|
+
* For `.csv` and `.xlsx` dataframes, it automatically separates and filters arguments for reading and writing so your code does not crash.
|
|
73
|
+
|
|
74
|
+
### `pyupdate(d1, d2)`
|
|
75
|
+
* **Description:** A helper function that merges two dictionaries recursively.
|
|
76
|
+
* **Capabilities:**
|
|
77
|
+
* If the same key exists in both dictionaries, it combines their values into a list or extends them instead of overwriting.
|
|
78
|
+
* Safely merges Python lists, tuples, sets, frozensets, and deques.
|
|
79
|
+
* Supports deep nested dictionary updates at any level.
|
|
80
|
+
|
|
81
|
+
### `make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres')`
|
|
82
|
+
* **Description:** Creates a connection object (engine) for your database using SQLAlchemy.
|
|
83
|
+
* **Capabilities:**
|
|
84
|
+
* Supports 3 popular database systems: PostgreSQL/Postgres, MySQL, and SQLite.
|
|
85
|
+
* Automatically builds the correct connection string URL so you do not have to memorize syntax.
|
|
86
|
+
|
|
87
|
+
### `sqlread(query, db_name, **kwargs)`
|
|
88
|
+
* **Description:** Runs an SQL query and returns the result table as a `pandas.DataFrame`.
|
|
89
|
+
* **Capabilities:**
|
|
90
|
+
* Automatically opens and closes the database connection for you.
|
|
91
|
+
* Accepts all configuration parameters from `make_sqlengine`.
|
|
92
|
+
|
|
93
|
+
### `sqlrewrite(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
94
|
+
* **Description:** Replaces an old table in the database with a new DataFrame.
|
|
95
|
+
* **Capabilities:**
|
|
96
|
+
* Uploads data in small parts (chunks) to protect your computer's RAM.
|
|
97
|
+
* Uses the fast multi insert method to send data to the database quickly.
|
|
98
|
+
|
|
99
|
+
### `sqladd(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
100
|
+
* **Description:** Appends new rows from a DataFrame to the end of an existing database table.
|
|
101
|
+
* **Capabilities:**
|
|
102
|
+
* Never deletes old database data; it only appends.
|
|
103
|
+
* Uses the same fast chunk-by-chunk processing system as `sqlrewrite`.
|
|
104
|
+
|
|
105
|
+
### `transform_from_sql(filepath, query, db_name, **kwargs)`
|
|
106
|
+
* **Description:** Takes data from a database query and saves it directly into a file.
|
|
107
|
+
* **Capabilities:**
|
|
108
|
+
* Exports database tables to `.csv`, `.parquet`, or styled `.xlsx` with one line of code.
|
|
109
|
+
* Automatically filters valid writing parameters depending on the chosen file extension.
|
|
110
|
+
|
|
111
|
+
### `transform_to_sql(filepath, table_name, db_name, **kwargs)`
|
|
112
|
+
* **Description:** Reads data from a file and uploads it directly into a database table.
|
|
113
|
+
* **Capabilities:**
|
|
114
|
+
* Connects `pyread` and `sqlrewrite` together automatically.
|
|
115
|
+
* Detects and links file reading parameters with database writing rules.
|
|
116
|
+
|
|
117
|
+
### `onelist(lst)`
|
|
118
|
+
* **Description:** Takes a complex nested collection and flattens it into one simple, single list.
|
|
119
|
+
* **Capabilities:**
|
|
120
|
+
* Uses recursion to unpack structures of any depth.
|
|
121
|
+
* Unpacks list, tuple, set, frozenset, and deque all at once.
|
|
122
|
+
|
|
123
|
+
### `super_round(value, num=0)`
|
|
124
|
+
* **Description:** Rounds numbers using standard symmetric school math rules (where 0.5 always rounds up away from zero).
|
|
125
|
+
* **Capabilities:**
|
|
126
|
+
* Bypasses Python's built-in "banker's rounding" (round-to-even) for predictable math results.
|
|
127
|
+
* Uses optimized string slices and list reversals for reliable parsing.
|
|
128
|
+
|
|
129
|
+
### `root(number, base=2, precision=2)`
|
|
130
|
+
* **Description:** Finds the root of a number with a specific degree and rounds the result.
|
|
131
|
+
* **Capabilities:**
|
|
132
|
+
* Supports square roots, cube roots, and higher degrees.
|
|
133
|
+
* Automatically blocks impossible operations (like even roots of negative numbers or degrees less than 2).
|
|
134
|
+
* Cleans the output using `super_round`.
|
|
135
|
+
|
|
136
|
+
### `quadratic_equation(a, b=0, c=0)`
|
|
137
|
+
* **Description:** Solves standard quadratic equations (ax² + bx + c = 0).
|
|
138
|
+
* **Capabilities:**
|
|
139
|
+
* Safely processes linear cases if a = 0 or b = 0.
|
|
140
|
+
* Returns `None` if there are no real roots, one number if there is one root, or a tuple `(x1, x2)` if there are two roots.
|
|
141
|
+
|
|
142
|
+
### `take_month(value)`
|
|
143
|
+
* **Description:** Converts months from any format to a numeric value.
|
|
144
|
+
* **Capabilities:** Supports Russian and English.
|
|
145
|
+
|
|
146
|
+
### `take_weekday(value, start_zero, start_sunday)`
|
|
147
|
+
* **Description:** Converts weekdays from any format to a numeric value.
|
|
148
|
+
* **Capabilities:**
|
|
149
|
+
* Supports Russian and English.
|
|
150
|
+
* Automatically handles different types of weekday indexing.
|
|
151
|
+
|
|
152
|
+
### `distributor(s)`
|
|
153
|
+
* **Description:** A finite state machine that creates values from string elements in a list.
|
|
154
|
+
* **Capabilities:** Distributes values by arrow and numeric type.
|
|
155
|
+
|
|
156
|
+
### `work_timezone1(value, to_tz, from_tz)`
|
|
157
|
+
* **Description:** Converts from one time zone to another and assigns the destination time zone to the result.
|
|
158
|
+
* **Capabilities:** Supports many different time zones.
|
|
159
|
+
|
|
160
|
+
### `work_timezone2(value, keyword, to_tz, from_tz)`
|
|
161
|
+
* **Description:** Converts a datetime object to a string.
|
|
162
|
+
* **Capabilities:** The result depends on the parameters and the specified datetime object type.
|
|
163
|
+
|
|
164
|
+
### `relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now', from_tz=none, to_tz=none)`
|
|
165
|
+
* **Description:** Converts from relative string dates and times to a DateTime object.
|
|
166
|
+
* * **Capabilities:**
|
|
167
|
+
* Supports Russian and English.
|
|
168
|
+
* Many operations with relative dates and times.
|
|
169
|
+
|
|
170
|
+
### `make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False)`
|
|
171
|
+
* **Description:** Converts various forms of string dates to a datetime object.
|
|
172
|
+
* **Capabilities:**
|
|
173
|
+
* Supports Russian and English.
|
|
174
|
+
* Supports the current date and any date specified for calculations with other dates.
|
|
175
|
+
* Includes many features, including the internal functions relative_datetime, take_month, and take_weekday.
|
|
176
|
+
* Handling short year entries using the century parameter.
|
|
177
|
+
* Arrangement of year, month, day, day of the week, and week numbering.
|
|
178
|
+
|
|
179
|
+
### `make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None)`
|
|
180
|
+
* **Description:** Converts various forms of string times to a time object.
|
|
181
|
+
* **Capabilities:**
|
|
182
|
+
* Supports Russian and English.
|
|
183
|
+
* Supports the current time and specifies any time for calculations with other times.
|
|
184
|
+
* Includes many features, including the internal functions relative_time and distributor.
|
|
185
|
+
* Smart validation of time unit ranges.
|
|
186
|
+
* Working with time zones and automatic determination of the local time zone.
|
|
187
|
+
|
|
188
|
+
### `make_datetime(value, *, order_date='yMD', order_time='hms', century=21, isFirstTime=false, start_sunday=false, start_zero=false, current_datetime='now', from_tz=none, to_tz=none)`
|
|
189
|
+
* **Description:** Converts from different forms String dates + time to the DateTime object.
|
|
190
|
+
* **Capabilities:**
|
|
191
|
+
* Supports Russian and English.
|
|
192
|
+
* Support the current date and time and prescribing any dates and times for calculation with other dates and times.
|
|
193
|
+
* Includes a lot of functionality, including internal functions Relative_DateTime, make_date, make_time, work_timezone1 and work_timezone2.
|
|
194
|
+
|
|
195
|
+
## Русский
|
|
196
|
+
## UltraPython: утилиты файлов, баз данных и математики 🐍
|
|
197
|
+
|
|
198
|
+
UltraPython — это простая и полезная библиотека для Python. Она помогает работать с различными файлами, подключаться к базам данных и выполнять математические операции без написания длинного кода. Отлично подходит для автоматизации ваших повседневных задач программирования.
|
|
199
|
+
|
|
200
|
+
> **Примечание:** Для работы библиотеки требуется Python 3.10+, так как в ней используется современный механизм сопоставления шаблонов (match-case).
|
|
201
|
+
|
|
202
|
+
## Основные возможности
|
|
203
|
+
|
|
204
|
+
* **Универсальные файлы:** Легкое чтение, запись и добавление данных в `.txt`, `.json`, `.pickle`, `.csv`, `.parquet` и `.xlsx` (Excel).
|
|
205
|
+
* **Красивый Excel:** Автоматически подбирает ширину колонок и добавляет красивые шрифты и цвета в таблицы.
|
|
206
|
+
* **Простая работа с SQL:** Подключение к PostgreSQL, MySQL или SQLite и быстрый перенос данных между файлами и базой.
|
|
207
|
+
* **Полезная математика:** Удобные функции для округления чисел, поиска корней и решения уравнений.
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Описание функций и их возможностей
|
|
212
|
+
|
|
213
|
+
### `pyread(filename, *, encoding='utf-8', as_list=False, **kwargs)`
|
|
214
|
+
* **Описание:** Читает данные из файла. Автоматически определяет нужный формат по его расширению.
|
|
215
|
+
* **Возможности:**
|
|
216
|
+
* Работает с 6 популярными форматами: `.txt`, `.json`, `.pickle`, `.csv`, `.parquet` и `.xlsx`.
|
|
217
|
+
* Если читать `.txt` с параметром `as_list=True`, функция автоматически разобьет текст на список строк.
|
|
218
|
+
* При чтении Excel с одним листом автоматически извлекает его как чистый DataFrame, а не словарь.
|
|
219
|
+
* Пробрасывает дополнительные параметры (`**kwargs`) во внутренние методы `pandas`.
|
|
220
|
+
|
|
221
|
+
### `pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, ...)`
|
|
222
|
+
* **Описание:** Полностью удаляет старое содержимое файла и записывает в него новые данные.
|
|
223
|
+
* **Возможности:**
|
|
224
|
+
* Поддерживает запись строк/списков в `.txt`, словарей в `.json`/`.pickle` и таблиц в `.csv`/`.parquet`/`.xlsx`.
|
|
225
|
+
* При сохранении в Excel автоматически наводит красоту: делает жирные заголовки, рамки ячеек, настраивает цвета и шрифты.
|
|
226
|
+
* Автоматически растягивает ширину колонок Excel под самый длинный текст в столбце.
|
|
227
|
+
* Сама выставляет форматы данных для ячеек Excel (текст, целые числа, дроби, даты и время).
|
|
228
|
+
|
|
229
|
+
### `pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs)`
|
|
230
|
+
* **Описание:** Добавляет новые данные в конец существующего файла без удаления старой информации.
|
|
231
|
+
* **Возможности:**
|
|
232
|
+
* В `.txt` файлах просто дописывает новые строки в самый конец.
|
|
233
|
+
* В `.json` и `.pickle` сначала считывает старые данные, безопасно объединяет их с новыми через `pyupdate` и перезаписывает файл.
|
|
234
|
+
* Для таблиц `.csv` и `.xlsx` автоматически разделяет и фильтрует аргументы чтения и записи, предотвращая ошибки.
|
|
235
|
+
|
|
236
|
+
### `pyupdate(d1, d2)`
|
|
237
|
+
* **Описание:** Помощник для рекурсивного (глубокого) объединения двух словарей.
|
|
238
|
+
* **Возможности:**
|
|
239
|
+
* Если ключи в словарях совпадают, функция не перезаписывает данные, а объединяет их элементы в один общий список.
|
|
240
|
+
* Безопасно работает со структурами `list`, `tuple`, `set`, `frozenset` и `deque`.
|
|
241
|
+
* Поддерживает слияние вложенных словарей на любой глубине.
|
|
242
|
+
|
|
243
|
+
### `make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres')`
|
|
244
|
+
* **Описание:** Создает объект подключения (engine) к базе данных через SQLAlchemy.
|
|
245
|
+
* **Возможности:**
|
|
246
|
+
* Поддерживает 3 популярные СУБД: PostgreSQL/Postgres, MySQL и SQLite.
|
|
247
|
+
* Сама собирает правильную строку подключения, избавляя вас от необходимости писать её вручную.
|
|
248
|
+
|
|
249
|
+
### `sqlread(query, db_name, **kwargs)`
|
|
250
|
+
* **Описание:** Выполняет SQL-запрос и возвращает полученную таблицу в виде `pandas.DataFrame`.
|
|
251
|
+
* **Возможности:**
|
|
252
|
+
* Сама открывает и закрывает соединение с базой данных «под капотом».
|
|
253
|
+
* Принимает все те же настройки подключения, что и `make_sqlengine`.
|
|
254
|
+
|
|
255
|
+
### `sqlrewrite(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
256
|
+
* **Описание:** Полностью удаляет старую таблицу в базе данных и записывает на её место новый DataFrame.
|
|
257
|
+
* **Возможности:**
|
|
258
|
+
* Загружает данные небольшими частями (chunks), что защищает оперативную память компьютера от перегрузки.
|
|
259
|
+
* Использует быстрый метод `multi` для ускоренной пакетной вставки строк в БД.
|
|
260
|
+
|
|
261
|
+
### `sqladd(table_name, new_value, db_name, ..., chunksize=50000, **kwargs)`
|
|
262
|
+
* **Описание:** Добавляет новые строки из DataFrame в конец существующей таблицы в базе данных.
|
|
263
|
+
* **Возможности:**
|
|
264
|
+
* Никогда не удаляет старые данные в БД, только дописывает новые.
|
|
265
|
+
* Использует ту же производительную систему разбивки на чанки, что и `sqlrewrite`.
|
|
266
|
+
|
|
267
|
+
### `transform_from_sql(filepath, query, db_name, **kwargs)`
|
|
268
|
+
* **Описание:** Берет данные из базы данных по SQL-запросу и сохраняет их напрямую в файл.
|
|
269
|
+
* **Возможности:**
|
|
270
|
+
* Экспортирует таблицы из БД в файлы `.csv`, `.parquet` или стилизованный `.xlsx` одной строчкой кода.
|
|
271
|
+
* Сама подбирает корректные параметры записи в зависимости от выбранного расширения файла.
|
|
272
|
+
|
|
273
|
+
### `transform_to_sql(filepath, table_name, db_name, **kwargs)`
|
|
274
|
+
* **Описание:** Читает данные из файла и сразу загружает их в таблицу базы данных.
|
|
275
|
+
* **Возможности:**
|
|
276
|
+
* Автоматически объединяет логику функций `pyread` и `sqlrewrite`.
|
|
277
|
+
* Самостоятельно связывает параметры чтения файлов с правилами записи в SQL.
|
|
278
|
+
|
|
279
|
+
### `onelist(lst)`
|
|
280
|
+
* **Описание:** Принимает сложную вложенную коллекцию и превращает её в один плоский простой список.
|
|
281
|
+
* **Возможности:**
|
|
282
|
+
* Использует рекурсию, позволяя разбирать структуры любой глубины вложенности.
|
|
283
|
+
* Успешно извлекает элементы из `list`, `tuple`, `set`, `frozenset` и `deque`.
|
|
284
|
+
|
|
285
|
+
### `super_round(value, num=0)`
|
|
286
|
+
* **Описание:** Округляет числа по стандартным школьным правилам математики (где 0.5 всегда округляется в большую сторону от нуля).
|
|
287
|
+
* **Возможности:**
|
|
288
|
+
* Позволяет обойти встроенное в Python «банковское округление» (к ближайшему четному) для получения предсказуемых результатов.
|
|
289
|
+
* Использует строковые срезы и развороты списков для точного разбора долей числа.
|
|
290
|
+
|
|
291
|
+
### `root(number, base=2, precision=2)`
|
|
292
|
+
* **Описание:** Находит корень числа любой степени и округляет итоговый результат.
|
|
293
|
+
* **Возможности:**
|
|
294
|
+
* Считает квадратные, кубические и любые корни высших степеней.
|
|
295
|
+
* Автоматически блокирует невозможные операции (например, извлечение четного корня из отрицательного числа или степень корня меньше 2).
|
|
296
|
+
* Финально обрабатывает результат через `super_round`.
|
|
297
|
+
|
|
298
|
+
### `quadratic_equation(a, b=0, c=0)`
|
|
299
|
+
* **Описание:** Решает стандартные квадратные уравнения (ax² + bx + c = 0).
|
|
300
|
+
* **Возможности:**
|
|
301
|
+
* Безопасно обрабатывает линейные случаи, если коэффициенты `a` или `b` равны нулю.
|
|
302
|
+
* Возвращает `None`, если вещественных корней нет, одно число при единственном корне или кортеж `(x1, x2)`, если корней два.
|
|
303
|
+
|
|
304
|
+
### `take_month(value)`
|
|
305
|
+
* **Описание:** Преобразовывает из любых форматов месяцев в числовом виде.
|
|
306
|
+
* **Возможности:** Поддерживает русский и английский языки.
|
|
307
|
+
|
|
308
|
+
### `take_weekday(value, start_zero, start_sunday)`
|
|
309
|
+
* **Описание:** Преобразует дни недели из любого формата в числовое значение.
|
|
310
|
+
* **Возможности:**
|
|
311
|
+
* Поддерживает русский и английский языки.
|
|
312
|
+
* Автоматически обрабатывает различные типы индексации дней недели.
|
|
313
|
+
|
|
314
|
+
### `distributor(s)`
|
|
315
|
+
* **Описание:** Конечный автомат, который создаёт значения из элементов строки в список.
|
|
316
|
+
* **Возможности:** Распределяет значения по стрелковому и числовому виду.
|
|
317
|
+
|
|
318
|
+
### `work_timezone1(value, to_tz, from_tz)`
|
|
319
|
+
* **Описание:** Переводит из одного часового пояса в другой и присваивает в конце результата конечный часовой пояс.
|
|
320
|
+
* **Возможности:** Поддерживает множество различных часовых поясов.
|
|
321
|
+
|
|
322
|
+
### `work_timezone2(value, keyword, to_tz, from_tz)`
|
|
323
|
+
* **Описание:** Преобразовывает из datetime объекта в строковой тип.
|
|
324
|
+
* **Возможности:** Результат зависит от параметров и определённого вида datetime объекта.
|
|
325
|
+
|
|
326
|
+
### `relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now', from_tz=None, to_tz=None)`
|
|
327
|
+
* **Описание:** Преобразовывает из относительных строковых дат и времён в объект datetime.
|
|
328
|
+
* **Возможности:**
|
|
329
|
+
* Поддерживает русский и английский языки.
|
|
330
|
+
* Множество операций с относительными датами и временами.
|
|
331
|
+
|
|
332
|
+
### `make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False)`
|
|
333
|
+
* **Описание:** Преобразовывает из различных форм строковых дат в объект datetime.
|
|
334
|
+
* **Возможности:**
|
|
335
|
+
* Поддерживает русский и английский языки.
|
|
336
|
+
* Поддержка текущей даты и прописывание любой даты для расчёта с остальными датами.
|
|
337
|
+
* Включает множество функционалов, в том числе внутренние функции relative_date, take_month, take_weekday.
|
|
338
|
+
* Обработка коротких записей годов благодаря параметру century.
|
|
339
|
+
* Расстановка положений года, месяца, дня, дня недели и нумерации недель.
|
|
340
|
+
|
|
341
|
+
### `make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None)`
|
|
342
|
+
* **Описание:** Преобразовывает из различных форм строковых времён в объект time.
|
|
343
|
+
* **Возможности:**
|
|
344
|
+
* Поддерживает русский и английский языки.
|
|
345
|
+
* Поддержка текущего времени и прописывание любого времени для расчёта с остальными временами.
|
|
346
|
+
* Включает множество функционалов, в том числе внутренние функции relative_datetime, work_timezone1, work_timezone2, distributor.
|
|
347
|
+
* Умная проверка диапазона единиц времени.
|
|
348
|
+
* Работа с часовыми поясами и автоматическое определение локального часового пояса.
|
|
349
|
+
|
|
350
|
+
### `make_datetime(value, *, order_date='ymd', order_time='HMS', century=21, isfirsttime=False, start_sunday=False, start_zero=False, current_datetime='now', from_tz=None, to_tz=None)`
|
|
351
|
+
* **Описание:** Преобразовывает из различных форм строковых дат + времён в объект datetime.
|
|
352
|
+
* **Возможности:**
|
|
353
|
+
* Поддерживает русский и английский языки.
|
|
354
|
+
* Поддержка текущих даты и времени и прописывание любых дат и времён для расчёта с остальными датами и временами.
|
|
355
|
+
* Включает множество функционалов, в том числе внутренние функции relative_datetime, make_date, make_time, work_timezone1 иwork_timezone2.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
ultrapython/__init__.py,sha256=MIOwjF_xvWHSEkZqlFu_X3zZS8JuCONdaWoPqYfvQkM,27
|
|
2
|
+
ultrapython/ultrapython.py,sha256=01K5YAUZtJjBz8FLiCrekRojew05mNZf6v7XYOMwsaY,35843
|
|
3
|
+
ultrapython-1.8.5.dist-info/METADATA,sha256=gR-6Hr8Wn3xzs0d031rNJVsif_qYe6ED9Qb-zkPQRmM,26662
|
|
4
|
+
ultrapython-1.8.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
ultrapython-1.8.5.dist-info/licenses/LICENSE,sha256=K4KZRD-7-Tl2Zof7G-kwqED2hg2cBSvmD0WYVGyaL1g,1076
|
|
6
|
+
ultrapython-1.8.5.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abdyrahym Begenjov
|
|
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.
|