UltraPython 1.8.5__tar.gz → 1.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ultrapython-1.8.5 → ultrapython-1.9.0}/PKG-INFO +30 -2
- {ultrapython-1.8.5 → ultrapython-1.9.0}/README.md +28 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/pyproject.toml +2 -2
- ultrapython-1.9.0/ultrapython.py +904 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/.github/workflows/publish.yml +0 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/.gitignore +0 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/LICENSE +0 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/src/ultrapython/__init__.py +0 -0
- {ultrapython-1.8.5 → ultrapython-1.9.0}/src/ultrapython/ultrapython.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
|
-
Name:
|
|
3
|
-
Version: 1.
|
|
2
|
+
Name: ultrapython
|
|
3
|
+
Version: 1.9.0
|
|
4
4
|
Summary: UltraPython: Utilities of Files, Databases, and Math
|
|
5
5
|
Project-URL: Homepage, https://github.com
|
|
6
6
|
Author: Abdyrahym Begenjov
|
|
@@ -192,6 +192,20 @@ UltraPython is a simple and helpful Python library. It helps you work with diffe
|
|
|
192
192
|
* Support the current date and time and prescribing any dates and times for calculation with other dates and times.
|
|
193
193
|
* Includes a lot of functionality, including internal functions Relative_DateTime, make_date, make_time, work_timezone1 and work_timezone2.
|
|
194
194
|
|
|
195
|
+
### `convert_units(num, value1=None, value2=None, auto=False, round_value=None)`
|
|
196
|
+
* **Description:** Converts from one unit of measurement to another.
|
|
197
|
+
* * **Capabilities:**
|
|
198
|
+
* Supports Russian and English.
|
|
199
|
+
* Supports rounding to n and automatic recognition of the original unit of measurement in the text version of the num parameter.
|
|
200
|
+
* Smart checking for correct unit relationships.
|
|
201
|
+
* Conversion from US to international units of measurement and vice versa.
|
|
202
|
+
|
|
203
|
+
### `freecopy(obj, memo=None)`
|
|
204
|
+
* **Description:** Performs deep copying of elements and data structures.
|
|
205
|
+
* **Capabilities:**
|
|
206
|
+
* Supports all known data structures.
|
|
207
|
+
* * No recursion errors.
|
|
208
|
+
|
|
195
209
|
## Русский
|
|
196
210
|
## UltraPython: утилиты файлов, баз данных и математики 🐍
|
|
197
211
|
|
|
@@ -353,3 +367,17 @@ UltraPython — это простая и полезная библиотека
|
|
|
353
367
|
* Поддерживает русский и английский языки.
|
|
354
368
|
* Поддержка текущих даты и времени и прописывание любых дат и времён для расчёта с остальными датами и временами.
|
|
355
369
|
* Включает множество функционалов, в том числе внутренние функции relative_datetime, make_date, make_time, work_timezone1 иwork_timezone2.
|
|
370
|
+
|
|
371
|
+
### `convert_units(num, value1=None, value2=None, auto=False, round_value=None)`
|
|
372
|
+
* **Описание:** Конвертирует из одной единицы измерения в другую.
|
|
373
|
+
* **Возможности:**
|
|
374
|
+
* Поддерживает русский и английский языки.
|
|
375
|
+
* Поддержка округления до n числа и автоматическим распознаванием исходной единицы измерения в текстовом варианте параметра num.
|
|
376
|
+
* Умная проверка на правильность соотношении единиц измерений.
|
|
377
|
+
* Преобразование из американской единицы измерений в международный и наоборот.
|
|
378
|
+
|
|
379
|
+
### `freecopy(obj, memo=None)`
|
|
380
|
+
* **Описание:** Выполняет глубокое копирование элементов и структур данных.
|
|
381
|
+
* **Возможности:**
|
|
382
|
+
* Поддержка всех известных структур данных.
|
|
383
|
+
* Отсутствие ошибок из-за рекурсии.
|
|
@@ -156,6 +156,20 @@ UltraPython is a simple and helpful Python library. It helps you work with diffe
|
|
|
156
156
|
* Support the current date and time and prescribing any dates and times for calculation with other dates and times.
|
|
157
157
|
* Includes a lot of functionality, including internal functions Relative_DateTime, make_date, make_time, work_timezone1 and work_timezone2.
|
|
158
158
|
|
|
159
|
+
### `convert_units(num, value1=None, value2=None, auto=False, round_value=None)`
|
|
160
|
+
* **Description:** Converts from one unit of measurement to another.
|
|
161
|
+
* * **Capabilities:**
|
|
162
|
+
* Supports Russian and English.
|
|
163
|
+
* Supports rounding to n and automatic recognition of the original unit of measurement in the text version of the num parameter.
|
|
164
|
+
* Smart checking for correct unit relationships.
|
|
165
|
+
* Conversion from US to international units of measurement and vice versa.
|
|
166
|
+
|
|
167
|
+
### `freecopy(obj, memo=None)`
|
|
168
|
+
* **Description:** Performs deep copying of elements and data structures.
|
|
169
|
+
* **Capabilities:**
|
|
170
|
+
* Supports all known data structures.
|
|
171
|
+
* * No recursion errors.
|
|
172
|
+
|
|
159
173
|
## Русский
|
|
160
174
|
## UltraPython: утилиты файлов, баз данных и математики 🐍
|
|
161
175
|
|
|
@@ -317,3 +331,17 @@ UltraPython — это простая и полезная библиотека
|
|
|
317
331
|
* Поддерживает русский и английский языки.
|
|
318
332
|
* Поддержка текущих даты и времени и прописывание любых дат и времён для расчёта с остальными датами и временами.
|
|
319
333
|
* Включает множество функционалов, в том числе внутренние функции relative_datetime, make_date, make_time, work_timezone1 иwork_timezone2.
|
|
334
|
+
|
|
335
|
+
### `convert_units(num, value1=None, value2=None, auto=False, round_value=None)`
|
|
336
|
+
* **Описание:** Конвертирует из одной единицы измерения в другую.
|
|
337
|
+
* **Возможности:**
|
|
338
|
+
* Поддерживает русский и английский языки.
|
|
339
|
+
* Поддержка округления до n числа и автоматическим распознаванием исходной единицы измерения в текстовом варианте параметра num.
|
|
340
|
+
* Умная проверка на правильность соотношении единиц измерений.
|
|
341
|
+
* Преобразование из американской единицы измерений в международный и наоборот.
|
|
342
|
+
|
|
343
|
+
### `freecopy(obj, memo=None)`
|
|
344
|
+
* **Описание:** Выполняет глубокое копирование элементов и структур данных.
|
|
345
|
+
* **Возможности:**
|
|
346
|
+
* Поддержка всех известных структур данных.
|
|
347
|
+
* Отсутствие ошибок из-за рекурсии.
|
|
@@ -0,0 +1,904 @@
|
|
|
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
|
+
units={
|
|
102
|
+
'length': (
|
|
103
|
+
{
|
|
104
|
+
'nm': 1, 'nanometer': 1, 'nanometers': 1, 'нм': 1, 'нанометр': 1, 'нанометра': 1, 'нанометров': 1,
|
|
105
|
+
'um': 2, 'micrometer': 2, 'micrometers': 2, 'мкм': 2, 'микрометр': 2, 'микрометра': 2, 'микрометров': 2,
|
|
106
|
+
'mm': 3, 'millimeter': 3, 'millimeters': 3, 'мм': 3, 'миллиметр': 3, 'миллиметра': 3, 'миллиметров': 3,
|
|
107
|
+
'cm': 4, 'centimeter': 4, 'centimeters': 4, 'см': 4, 'сантиметр': 4, 'сантиметра': 4, 'сантиметров': 4,
|
|
108
|
+
'dm': 5, 'decimeter': 5, 'decimeters': 5, 'дм': 5, 'дециметр': 5, 'дециметра': 5, 'дециметров': 5,
|
|
109
|
+
'm': 6, 'meter': 6, 'meters': 6, 'м': 6, 'метр': 6, 'метра': 6, 'метров': 6,
|
|
110
|
+
'km': 7, 'kilometer': 7, 'kilometers': 7, 'км': 7, 'километр': 7, 'километра': 7, 'километров': 7
|
|
111
|
+
},
|
|
112
|
+
{1: 1000, 2: 1000, 3: 10, 4: 10, 5: 10, 6: 1000}
|
|
113
|
+
),
|
|
114
|
+
'mass': (
|
|
115
|
+
{
|
|
116
|
+
'mg': 1, 'milligram': 1, 'milligrams': 1, 'мг': 1, 'миллиграмм': 1, 'миллиграмма': 1, 'миллиграммов': 1,
|
|
117
|
+
'g': 2, 'gram': 2, 'grams': 2, 'г': 2, 'гр': 2, 'грамм': 2, 'грамма': 2, 'граммов': 2,
|
|
118
|
+
'kg': 3, 'kilogram': 3, 'kilograms': 3, 'кг': 3, 'килограмм': 3, 'килограмма': 3, 'килограммов': 3,
|
|
119
|
+
'c': 4, 'centner': 4, 'centners': 4, 'ц': 4, 'центнер': 4, 'центнера': 4, 'центнеров': 4,
|
|
120
|
+
't': 5, 'ton': 5, 'tons': 5, 'т': 5, 'тонна': 5, 'тонны': 5, 'тонн': 5
|
|
121
|
+
},
|
|
122
|
+
{1: 1000, 2: 1000, 3: 100, 4: 10}
|
|
123
|
+
),
|
|
124
|
+
'time': (
|
|
125
|
+
{
|
|
126
|
+
'ms': 1, 'millisecond': 1, 'milliseconds': 1, 'мс': 1, 'миллисекунда': 1, 'миллисекунды': 1, 'миллисекунд': 1,
|
|
127
|
+
's': 2, 'sec': 2, 'second': 2, 'seconds': 2, 'с': 2, 'сек': 2, 'секунда': 2, 'секунды': 2, 'секунд': 2,
|
|
128
|
+
'min': 3, 'minute': 3, 'minutes': 3, 'мин': 3, 'минута': 3, 'минуты': 3, 'минут': 3,
|
|
129
|
+
'h': 4, 'hour': 4, 'hours': 4, 'ч': 4, 'час': 4, 'часа': 4, 'часов': 4,
|
|
130
|
+
'd': 5, 'day': 5, 'days': 5, 'д': 5, 'дн': 5, 'день': 5, 'дня': 5, 'дней': 5,
|
|
131
|
+
'y': 6, 'year': 6, 'years': 6, 'г': 6, 'год': 6, 'года': 6, 'лет': 6
|
|
132
|
+
},
|
|
133
|
+
{1: 1000, 2: 60, 3: 60, 4: 24, 5: 365.25}
|
|
134
|
+
),
|
|
135
|
+
'data': (
|
|
136
|
+
{
|
|
137
|
+
'bit': 1, 'bits': 1, 'бит': 1, 'бита': 1, 'битов': 1,
|
|
138
|
+
'b': 2, 'byte': 2, 'bytes': 2, 'б': 2, 'байт': 2, 'байта': 2, 'байтов': 2,
|
|
139
|
+
'kbit': 3, 'kilobit': 3, 'kilobits': 3, 'кбит': 3, 'килобит': 3, 'килобита': 3, 'килобитов': 3,
|
|
140
|
+
'kb': 4, 'kilobyte': 4, 'kilobytes': 4, 'кб': 4, 'килобайт': 4, 'килобайта': 4, 'килобайтов': 4,
|
|
141
|
+
'mbit': 5, 'megabit': 5, 'megabits': 5, 'мбит': 5, 'мегабит': 5, 'мегабита': 5, 'мегабитов': 5,
|
|
142
|
+
'mb': 6, 'megabyte': 6, 'megabytes': 6, 'мб': 6, 'мегабайт': 6, 'мегабайта': 6, 'мегабайтов': 6,
|
|
143
|
+
'gbit': 7, 'gigabit': 7, 'gigabits': 7, 'гбит': 7, 'гигабит': 7, 'гигабита': 7, 'гигабитов': 7,
|
|
144
|
+
'gb': 8, 'gigabyte': 8, 'gigabytes': 8, 'гб': 8, 'гигабайт': 8, 'гигабайта': 8, 'гигабайтов': 8,
|
|
145
|
+
'tbit': 9, 'terabit': 9, 'terabits': 9, 'тбит': 9, 'терабит': 9, 'терабита': 9, 'терабитов': 9,
|
|
146
|
+
'tb': 10, 'terabyte': 10, 'terabytes': 10, 'тб': 10, 'терабайт': 10, 'терабайта': 10, 'терабайтов': 10
|
|
147
|
+
},
|
|
148
|
+
{1: 8, 2: 128, 3: 8, 4: 128, 5: 8, 6: 128, 7: 8, 8: 128, 9: 8}
|
|
149
|
+
),
|
|
150
|
+
'area': (
|
|
151
|
+
{
|
|
152
|
+
'mm2': 1, 'sq mm': 1, 'square millimeter': 1, 'square millimeters': 1, 'мм2': 1, 'кв мм': 1, 'квадратный миллиметр': 1, 'квадратных миллиметров': 1,
|
|
153
|
+
'cm2': 2, 'sq cm': 2, 'square centimeter': 2, 'square centimeters': 2, 'см2': 2, 'кв см': 2, 'квадратный сантиметр': 2, 'квадратных сантиметров': 2,
|
|
154
|
+
'dm2': 3, 'sq dm': 3, 'square decimeter': 3, 'square decimeters': 3, 'дм2': 3, 'кв дм': 3, 'квадратный дециметр': 3, 'квадратных дециметров': 3,
|
|
155
|
+
'm2': 4, 'sq m': 4, 'square meter': 4, 'square meters': 4, 'м2': 4, 'кв м': 4, 'квадратный метр': 4, 'квадратных метров': 4,
|
|
156
|
+
'ar': 5, 'are': 5, 'ares': 5, 'ар': 5, 'ара': 5, 'аров': 5, 'сотка': 5, 'сотки': 5, 'соток': 5,
|
|
157
|
+
'ha': 6, 'hectare': 6, 'hectares': 6, 'га': 6, 'гектар': 6, 'гектара': 6, 'гектаров': 6,
|
|
158
|
+
'km2': 7, 'sq km': 7, 'square kilometer': 7, 'square kilometers': 7, 'км2': 7, 'кв км': 7, 'квадратный километр': 7, 'квадратных километров': 7
|
|
159
|
+
},
|
|
160
|
+
{1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100}
|
|
161
|
+
),
|
|
162
|
+
'volume': (
|
|
163
|
+
{
|
|
164
|
+
'mm3': 1, 'cubic millimeter': 1, 'cubic millimeters': 1, 'мм3': 1, 'куб мм': 1, 'кубический миллиметр': 1, 'кубических миллиметров': 1,
|
|
165
|
+
'ml': 2, 'milliliter': 2, 'milliliters': 2, 'мл': 2, 'миллилитр': 2, 'миллилитра': 2, 'миллилитров': 2,
|
|
166
|
+
'cm3': 2, 'cubic centimeter': 2, 'cubic centimeters': 2, 'см3': 2, 'куб см': 2, 'кубический сантиметр': 2, 'кубических сантиметров': 2,
|
|
167
|
+
'l': 3, 'liter': 3, 'liters': 3, 'л': 3, 'литр': 3, 'литра': 3, 'литров': 3,
|
|
168
|
+
'dm3': 3, 'cubic decimeter': 3, 'cubic decimeters': 3, 'дм3': 3, 'куб дм': 3, 'кубический дециметр': 3, 'кубических дециметров': 3,
|
|
169
|
+
'm3': 4, 'cubic meter': 4, 'cubic meters': 4, 'м3': 4, 'куб м': 4, 'кубический метр': 4, 'кубических метров': 4
|
|
170
|
+
},
|
|
171
|
+
{1: 1000, 2: 1000, 3: 1000}
|
|
172
|
+
),
|
|
173
|
+
'speed': (
|
|
174
|
+
{
|
|
175
|
+
'cm/s': 1, 'centimeter per second': 1, 'centimeters per second': 1, 'см/с': 1, 'см/сек': 1, 'сантиметр в секунду': 1, 'сантиметров в секунду': 1,
|
|
176
|
+
'm/s': 2, 'meter per second': 2, 'meters per second': 2, 'м/с': 2, 'м/сек': 2, 'метр в секунду': 2, 'метров в секунду': 2,
|
|
177
|
+
'km/h': 3, 'kilometer per hour': 3, 'kilometers per hour': 3, 'км/ч': 3, 'км/час': 3, 'километр в час': 3, 'километров в час': 3
|
|
178
|
+
},
|
|
179
|
+
{1: 100, 2: 3.6}
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def pyread(filename, *, encoding='utf-8', as_list=False, **kwargs):
|
|
185
|
+
match filename:
|
|
186
|
+
case filename if filename.endswith('.txt'):
|
|
187
|
+
with open(filename, 'r', encoding=encoding) as file:
|
|
188
|
+
result=file.read().strip()
|
|
189
|
+
return result if as_list==False else result.split('\n')
|
|
190
|
+
case filename if filename.endswith('.json'):
|
|
191
|
+
with open(filename, 'r', encoding=encoding) as file:
|
|
192
|
+
return json.load(file)
|
|
193
|
+
case filename if filename.endswith('.pickle'):
|
|
194
|
+
with open(filename, 'rb') as file:
|
|
195
|
+
return pickle.load(file)
|
|
196
|
+
case filename if filename.endswith('.csv'):
|
|
197
|
+
return read_csv(filename, encoding=encoding, **kwargs)
|
|
198
|
+
case filename if filename.endswith('.parquet'):
|
|
199
|
+
return read_parquet(filename, **kwargs)
|
|
200
|
+
case filename if filename.endswith('.xlsx'):
|
|
201
|
+
result=read_excel(filename, **kwargs)
|
|
202
|
+
if isinstance(result, dict) and len(result)==1:
|
|
203
|
+
result=[i for i in result.values()]
|
|
204
|
+
result=result[0]
|
|
205
|
+
return result
|
|
206
|
+
case _:
|
|
207
|
+
raise ValueError('Unsupported File!!!')
|
|
208
|
+
|
|
209
|
+
def pyadd(filename, value, *, encoding='utf-8', sheet_name=None, **kwargs):
|
|
210
|
+
match filename:
|
|
211
|
+
case filename if filename.endswith('.txt'):
|
|
212
|
+
with open(filename, 'a', encoding=encoding) as file:
|
|
213
|
+
match value:
|
|
214
|
+
case value if type(value) in data_types:
|
|
215
|
+
file.write(value)
|
|
216
|
+
case _:
|
|
217
|
+
file.writelines(value)
|
|
218
|
+
case filename if filename.endswith(('.json', '.pickle')):
|
|
219
|
+
file=pyread(filename, encoding=encoding)
|
|
220
|
+
file=pyupdate(file, value)
|
|
221
|
+
pyrewrite(filename, file)
|
|
222
|
+
case filename if filename.endswith('.csv'):
|
|
223
|
+
kw1={i: j for i, j in kwargs.items() if i in csvread_parameters}
|
|
224
|
+
file=pyread(filename, encoding=encoding, **kw1)
|
|
225
|
+
file=concat([file, value])
|
|
226
|
+
kw2={i: j for i, j in kwargs.items() if i in csvrewrite_parameters}
|
|
227
|
+
pyrewrite(filename, file, **kw2)
|
|
228
|
+
case filename if filename.endswith('.parquet'):
|
|
229
|
+
makedirs(filename, exist_ok=True)
|
|
230
|
+
table=Table.from_pandas(value)
|
|
231
|
+
write_to_dataset(table, root_path=filename, **kwargs)
|
|
232
|
+
case filename if filename.endswith('.xlsx'):
|
|
233
|
+
value=[value] if not isinstance(value, list) else value
|
|
234
|
+
if sheet_name is None:
|
|
235
|
+
c=load_workbook(filename, read_only=True)
|
|
236
|
+
try:
|
|
237
|
+
sheet_name=c.sheetnames
|
|
238
|
+
finally:
|
|
239
|
+
c.close()
|
|
240
|
+
else:
|
|
241
|
+
sheet_name=[sheet_name] if not isinstance(sheet_name, list) else sheet_name
|
|
242
|
+
if len(value)==len(sheet_name):
|
|
243
|
+
kw1={i: j for i, j in kwargs.items() if i in excelread_parameters}
|
|
244
|
+
file=pyread(filename, sheet_name=sheet_name, **kw1)
|
|
245
|
+
df_list=[concat([i, j]) for i, j in zip(file.values(), value)]
|
|
246
|
+
kw2={i: j for i, j in kwargs.items() if i in excelrewrite_parameters}
|
|
247
|
+
pyrewrite(filename, df_list, sheet_name=sheet_name, **kw2)
|
|
248
|
+
else:
|
|
249
|
+
raise ValueError('The number of values should be equal to the number of sheet names!!!')
|
|
250
|
+
case _:
|
|
251
|
+
raise ValueError('Unsupported File!!!')
|
|
252
|
+
|
|
253
|
+
def pyupdate(d1, d2):
|
|
254
|
+
for i in d2:
|
|
255
|
+
if i in d1:
|
|
256
|
+
if isinstance(d1[i], data_structures) and isinstance(d2[i], data_structures):
|
|
257
|
+
d1[i]=d1[i]+d2[i]
|
|
258
|
+
elif isinstance(d1[i], data_structures) and isinstance(d2[i], data_types):
|
|
259
|
+
d1[i].append(d2[i])
|
|
260
|
+
elif isinstance(d1[i], data_types) and isinstance(d2[i], data_structures):
|
|
261
|
+
d1[i]=[d1[i]]
|
|
262
|
+
d1[i].extend(d2[i])
|
|
263
|
+
elif isinstance(d1[i], dict) and isinstance(d2[i], dict):
|
|
264
|
+
pyupdate(d1[i], d2[i])
|
|
265
|
+
else:
|
|
266
|
+
d1[i]=[d1[i], d2[i]]
|
|
267
|
+
else:
|
|
268
|
+
d1[i]=d2[i]
|
|
269
|
+
return d1
|
|
270
|
+
|
|
271
|
+
def pyrewrite(filename, value, *, encoding='utf-8', sheet_name=None, head_font='Arial', head_size=12,
|
|
272
|
+
head_font_color='black', head_cell_color='white', font='Arial', size=11, font_color='black',
|
|
273
|
+
cell_color='white', border_color='white', date_format='yyyy-mm-dd',
|
|
274
|
+
time_format='hh:mm:ss', **kwargs):
|
|
275
|
+
match filename:
|
|
276
|
+
case filename if filename.endswith('.txt'):
|
|
277
|
+
with open(filename, 'w', encoding=encoding) as file:
|
|
278
|
+
match value:
|
|
279
|
+
case value if type(value) in data_types:
|
|
280
|
+
file.write(value)
|
|
281
|
+
case _:
|
|
282
|
+
file.writelines(value)
|
|
283
|
+
case filename if filename.endswith('.json'):
|
|
284
|
+
with open(filename, 'w', encoding=encoding) as file:
|
|
285
|
+
json.dump(value, file)
|
|
286
|
+
case filename if filename.endswith('.pickle'):
|
|
287
|
+
with open(filename, 'wb') as file:
|
|
288
|
+
pickle.dump(value, file)
|
|
289
|
+
case filename if filename.endswith('.csv'):
|
|
290
|
+
value.to_csv(filename, encoding=encoding, **kwargs)
|
|
291
|
+
case filename if filename.endswith('.parquet'):
|
|
292
|
+
value.to_parquet(filename, **kwargs)
|
|
293
|
+
case filename if filename.endswith('.xlsx'):
|
|
294
|
+
value=[value] if not isinstance(value, list) else value
|
|
295
|
+
if sheet_name is None:
|
|
296
|
+
if exists(filename):
|
|
297
|
+
c=load_workbook(filename, read_only=True)
|
|
298
|
+
try:
|
|
299
|
+
sheet_name=c.sheetnames
|
|
300
|
+
finally:
|
|
301
|
+
c.close()
|
|
302
|
+
else:
|
|
303
|
+
sheet_name=[f'Sheet{i}' for i in range(1, len(value)+1)]
|
|
304
|
+
else:
|
|
305
|
+
sheet_name=[sheet_name] if not isinstance(sheet_name, list) else sheet_name
|
|
306
|
+
if len(value)==len(sheet_name):
|
|
307
|
+
ex={'mode': 'a', 'if_sheet_exists': 'replace'} if exists(filename) else {'mode': 'w'}
|
|
308
|
+
with ExcelWriter(filename, engine='openpyxl', **ex) as writer:
|
|
309
|
+
for i, j in zip(value, sheet_name):
|
|
310
|
+
i.to_excel(writer, sheet_name=j, index=False, **kwargs)
|
|
311
|
+
worksheet=writer.sheets[j]
|
|
312
|
+
header_font=Font(name=head_font, size=head_size, bold=True, color=colors[head_font_color])
|
|
313
|
+
header_fill=PatternFill(start_color=colors[head_cell_color],
|
|
314
|
+
end_color=colors[head_cell_color], fill_type='solid')
|
|
315
|
+
data_font=Font(name=font, size=size, color=colors[font_color])
|
|
316
|
+
data_fill=PatternFill(start_color=colors[cell_color],
|
|
317
|
+
end_color=colors[cell_color], fill_type='solid')
|
|
318
|
+
thin_side=Side(border_style='thin', color=colors[border_color])
|
|
319
|
+
border=Border(left=thin_side, right=thin_side, top=thin_side, bottom=thin_side)
|
|
320
|
+
center_alignment=Alignment(horizontal='center', vertical='center')
|
|
321
|
+
for col_idx in range(1, len(i.columns)+1):
|
|
322
|
+
cell=worksheet.cell(row=1, column=col_idx)
|
|
323
|
+
cell.font=header_font
|
|
324
|
+
cell.fill=header_fill
|
|
325
|
+
cell.alignment=center_alignment
|
|
326
|
+
cell.border=border
|
|
327
|
+
for row in range(2, len(i)+2):
|
|
328
|
+
for col in range(1, len(i.columns)+1):
|
|
329
|
+
cell=worksheet.cell(row=row, column=col)
|
|
330
|
+
cell.font=data_font
|
|
331
|
+
cell.fill=data_fill
|
|
332
|
+
cell.border=border
|
|
333
|
+
col_name=i.columns[col-1]
|
|
334
|
+
value_type=i[col_name].dtype
|
|
335
|
+
if str(value_type) in type_formats:
|
|
336
|
+
config=type_formats[str(value_type)]
|
|
337
|
+
elif str(value_type)=='datetime64[ns]':
|
|
338
|
+
valid_series=i[col_name].dropna()
|
|
339
|
+
first_value=valid_series[0] if not valid_series.empty else None
|
|
340
|
+
if first_value is not None:
|
|
341
|
+
date_list=[str(i.date()) for i in valid_series]
|
|
342
|
+
time_list=[str(i.time()) for i in valid_series]
|
|
343
|
+
if all(i==time_list[0] for i in time_list):
|
|
344
|
+
type_formats['datetime64[ns]']=date_format
|
|
345
|
+
elif all(i==date_list[0] for i in date_list):
|
|
346
|
+
type_formats['datetime64[ns]']=time_format
|
|
347
|
+
else:
|
|
348
|
+
type_formats['datetime64[ns]']=f'{date_format} {time_format}'
|
|
349
|
+
else:
|
|
350
|
+
type_formats['datetime64[ns]']='General'
|
|
351
|
+
config=type_formats['datetime64[ns]']
|
|
352
|
+
elif issubdtype(value_type, integer):
|
|
353
|
+
config=type_formats['integer']
|
|
354
|
+
elif issubdtype(value_type, floating):
|
|
355
|
+
config=type_formats['float']
|
|
356
|
+
else:
|
|
357
|
+
config=type_formats['default']
|
|
358
|
+
cell.number_format=config
|
|
359
|
+
for col in worksheet.columns:
|
|
360
|
+
max_len=max(len(str(cell.value or '')) for cell in col)
|
|
361
|
+
header_len=len(str(col[0].value or ''))
|
|
362
|
+
col_letter=col[0].column_letter
|
|
363
|
+
worksheet.column_dimensions[col_letter].width=max(max_len, header_len)+5
|
|
364
|
+
else:
|
|
365
|
+
raise ValueError('The number of values should be equal to the number of sheet names!!!')
|
|
366
|
+
case _:
|
|
367
|
+
raise ValueError('Unsupported File!!!')
|
|
368
|
+
|
|
369
|
+
pyread_parameters=[i for i in signature(pyread).parameters]
|
|
370
|
+
pyrewrite_parameters=[i for i in signature(pyrewrite).parameters]
|
|
371
|
+
excelrewrite_parameters=[i for i in signature(DataFrame.to_excel).parameters]+pyrewrite_parameters
|
|
372
|
+
excelrewrite_parameters.remove('kwargs')
|
|
373
|
+
|
|
374
|
+
def super_round(value, num=0):
|
|
375
|
+
if '.' not in str(value):
|
|
376
|
+
value=float(f'{value}.0')
|
|
377
|
+
n1=1 if value>=0 else -1
|
|
378
|
+
a, b=str(f"{abs(value)}").split('.')
|
|
379
|
+
if b=='0':
|
|
380
|
+
return int(a)
|
|
381
|
+
if len(b)<num+1:
|
|
382
|
+
b=b.ljust(len(b)+(num+1-len(b)), '0')
|
|
383
|
+
elif len(b)>num+1:
|
|
384
|
+
b=b[:num+1]
|
|
385
|
+
b_list=list(b[::-1])
|
|
386
|
+
if b_list[0] in ['5', '6', '7', '8', '9']:
|
|
387
|
+
n2=1
|
|
388
|
+
for i in range(1, len(b_list)):
|
|
389
|
+
b_list[i]=str(int(b_list[i])+n2)
|
|
390
|
+
if b_list[i]=='10':
|
|
391
|
+
b_list[i]='0'
|
|
392
|
+
n2=1
|
|
393
|
+
else:
|
|
394
|
+
n2=0
|
|
395
|
+
break
|
|
396
|
+
else:
|
|
397
|
+
n2=0
|
|
398
|
+
b_list[0]='0'
|
|
399
|
+
b_list=reversed(b_list)
|
|
400
|
+
result=f'{n2+int(a)}.{''.join(b_list)}'
|
|
401
|
+
return n1*float(result)
|
|
402
|
+
|
|
403
|
+
def root(number, base=2, precision=2):
|
|
404
|
+
if base<2:
|
|
405
|
+
raise ValueError("The degree of the root must be greater than or equal to 2!!!")
|
|
406
|
+
if number<0 and base%2==0:
|
|
407
|
+
raise ValueError("You can't extract the root of an even power from a negative number!!!")
|
|
408
|
+
else:
|
|
409
|
+
n=1 if number>=0 else -1
|
|
410
|
+
result=abs(number)**(1/base)
|
|
411
|
+
return super_round(n*result, precision)
|
|
412
|
+
|
|
413
|
+
def quadratic_equation(a, b=0, c=0):
|
|
414
|
+
if a==0:
|
|
415
|
+
if b==0:
|
|
416
|
+
return None
|
|
417
|
+
return -c/b
|
|
418
|
+
d=b**2-(4*a*c)
|
|
419
|
+
if d<0:
|
|
420
|
+
return None
|
|
421
|
+
elif d==0:
|
|
422
|
+
return -b/(2*a)
|
|
423
|
+
else:
|
|
424
|
+
x1=((-b)+root(d))/(2*a)
|
|
425
|
+
x2=((-b)-root(d))/(2*a)
|
|
426
|
+
return (x1, x2)
|
|
427
|
+
|
|
428
|
+
def onelist(lst):
|
|
429
|
+
result=[]
|
|
430
|
+
for i in lst:
|
|
431
|
+
if isinstance(i, data_structures):
|
|
432
|
+
result.extend(onelist(i))
|
|
433
|
+
else:
|
|
434
|
+
result.append(i)
|
|
435
|
+
return result
|
|
436
|
+
|
|
437
|
+
def make_sqlengine(db_name, db_user=None, db_password=None, db_host='localhost', db_port=5432, db_type='postgres'):
|
|
438
|
+
match db_type.lower():
|
|
439
|
+
case 'postgresql' | 'postgres':
|
|
440
|
+
db_path=f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
|
|
441
|
+
case 'mysql':
|
|
442
|
+
db_path=f"mysql+pymysql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
|
|
443
|
+
case 'sqlite':
|
|
444
|
+
db_path=f"sqlite:///{db_name}"
|
|
445
|
+
case _:
|
|
446
|
+
raise ValueError("Unsupported database type!!!")
|
|
447
|
+
return create_engine(db_path)
|
|
448
|
+
|
|
449
|
+
def sqlread(query, db_name, *, db_user=None, db_password=None, db_host='localhost',
|
|
450
|
+
db_port=5432, db_type='postgres', **kwargs):
|
|
451
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
452
|
+
result=read_sql(query, con=engine, **kwargs)
|
|
453
|
+
return result
|
|
454
|
+
|
|
455
|
+
def sqlrewrite(table_name, new_value, db_name, *, db_user=None, db_password=None,
|
|
456
|
+
db_host='localhost', db_port=5432, db_type='postgres', chunksize=50000, **kwargs):
|
|
457
|
+
kwargs.pop('if_exists', None)
|
|
458
|
+
kwargs.pop('method', None)
|
|
459
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
460
|
+
for n, i in enumerate(range(0, len(new_value), chunksize)):
|
|
461
|
+
chunk=new_value.iloc[i:i+chunksize]
|
|
462
|
+
mode="replace" if n==0 else "append"
|
|
463
|
+
chunk.to_sql(table_name, con=engine, if_exists=mode, index=False, method='multi', **kwargs)
|
|
464
|
+
|
|
465
|
+
sqlread_parameters=[i for i in signature(sqlread).parameters]
|
|
466
|
+
sqlrewrite_parameters=[i for i in signature(sqlrewrite).parameters]
|
|
467
|
+
|
|
468
|
+
def sqladd(table_name, new_value, db_name, *, db_user=None, db_password=None,
|
|
469
|
+
db_host='localhost', db_port=5432, db_type='postgres', chunksize=50000, **kwargs):
|
|
470
|
+
kwargs.pop('if_exists', None)
|
|
471
|
+
kwargs.pop('method', None)
|
|
472
|
+
engine=make_sqlengine(db_name, db_user, db_password, db_host, db_port, db_type)
|
|
473
|
+
for i in range(0, len(new_value), chunksize):
|
|
474
|
+
chunk=new_value.iloc[i:i+chunksize]
|
|
475
|
+
chunk.to_sql(table_name, con=engine, if_exists="append", index=False, method='multi', **kwargs)
|
|
476
|
+
|
|
477
|
+
def transform_from_sql(filepath, query, db_name, **kwargs):
|
|
478
|
+
match filepath:
|
|
479
|
+
case filepath if filepath.endswith('.csv'):
|
|
480
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_csv).parameters]
|
|
481
|
+
case filepath if filepath.endswith('.parquet'):
|
|
482
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_parquet).parameters]
|
|
483
|
+
case filepath if filepath.endswith('.xlsx'):
|
|
484
|
+
from_sql_parameters=[i for i in signature(DataFrame.to_excel).parameters]+pyrewrite_parameters
|
|
485
|
+
case _:
|
|
486
|
+
raise ValueError('Unsupported file!!!')
|
|
487
|
+
k1={i: j for i, j in kwargs.items() if i in sqlread_parameters}
|
|
488
|
+
result=sqlread(query, db_name, **k1)
|
|
489
|
+
k2={i: j for i, j in kwargs.items() if i in from_sql_parameters}
|
|
490
|
+
pyrewrite(filepath, result, **k2)
|
|
491
|
+
|
|
492
|
+
def transform_to_sql(filepath, table_name, db_name, **kwargs):
|
|
493
|
+
match filepath:
|
|
494
|
+
case filepath if filepath.endswith('.csv'):
|
|
495
|
+
to_sql_parameters=[i for i in signature(read_csv).parameters]
|
|
496
|
+
case filepath if filepath.endswith('.parquet'):
|
|
497
|
+
to_sql_parameters=[i for i in signature(read_parquet).parameters]
|
|
498
|
+
case filepath if filepath.endswith('.xlsx'):
|
|
499
|
+
to_sql_parameters=[i for i in signature(read_excel).parameters]+pyread_parameters
|
|
500
|
+
case _:
|
|
501
|
+
raise ValueError('Unsupported file!!!')
|
|
502
|
+
k1={i: j for i, j in kwargs.items() if i in to_sql_parameters}
|
|
503
|
+
result=pyread(filepath, **k1)
|
|
504
|
+
k2={i: j for i, j in kwargs.items() if i in sqlrewrite_parameters}
|
|
505
|
+
sqlrewrite(table_name, result, db_name, **k2)
|
|
506
|
+
|
|
507
|
+
def take_month(value):
|
|
508
|
+
if value in ('january', 'jan', 'январь', 'января', 'янв', '01', '1'):
|
|
509
|
+
return [1, 31]
|
|
510
|
+
elif value in ('february', 'feb', 'февраль', 'февраля', 'фев', '02', '2'):
|
|
511
|
+
return [2, 28]
|
|
512
|
+
elif value in ('march', 'mar', 'март', 'марта', 'мар', '03', '3'):
|
|
513
|
+
return [3, 31]
|
|
514
|
+
elif value in ('april', 'apr', 'апрель', 'апреля', 'апр', '04', '4'):
|
|
515
|
+
return [4, 30]
|
|
516
|
+
elif value in ('may', 'май', 'мая', '05', '5'):
|
|
517
|
+
return [5, 31]
|
|
518
|
+
elif value in ('june', 'jun', 'июнь', 'июня', 'июн', '06', '6'):
|
|
519
|
+
return [6, 30]
|
|
520
|
+
elif value in ('july', 'jul', 'июль', 'июля', 'июл', '07', '7'):
|
|
521
|
+
return [7, 31]
|
|
522
|
+
elif value in ('august', 'aug', 'август', 'августа', 'авг', '08', '8'):
|
|
523
|
+
return [8, 31]
|
|
524
|
+
elif value in ('september', 'sep', 'сентябрь', 'сентября', 'сен', '09', '9'):
|
|
525
|
+
return [9, 30]
|
|
526
|
+
elif value in ('october', 'oct', 'октябрь', 'октября', 'окт', '10'):
|
|
527
|
+
return [10, 31]
|
|
528
|
+
elif value in ('november', 'nov', 'ноябрь', 'ноября', 'ноя', '11'):
|
|
529
|
+
return [11, 30]
|
|
530
|
+
elif value in ('december', 'dec', 'декабрь', 'декабря', 'дек', '12'):
|
|
531
|
+
return [12, 31]
|
|
532
|
+
else:
|
|
533
|
+
raise ValueError('The entered month does not exist!!!')
|
|
534
|
+
|
|
535
|
+
def take_weekday(value, start_zero, start_sunday):
|
|
536
|
+
numweek_list=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12',
|
|
537
|
+
'01', '02', '03', '04', '05', '06', '07', '08', '09']
|
|
538
|
+
if value.startswith(('monday', 'mon', 'mo', 'понедельник', 'пон', 'пн', '01', '1')):
|
|
539
|
+
result=1
|
|
540
|
+
elif value.startswith(('tuesday', 'tue', 'tu', 'вторник', 'вто', 'вт', '02', '2')):
|
|
541
|
+
result=2
|
|
542
|
+
elif value.startswith(('wednesday', 'wed', 'we', 'среда', 'сре', 'ср', '03', '3')):
|
|
543
|
+
result=3
|
|
544
|
+
elif value.startswith(('thursday', 'thu', 'th', 'четверг', 'чет', 'чт', '04', '4')):
|
|
545
|
+
result=4
|
|
546
|
+
elif value.startswith(('friday', 'fri', 'fr', 'пятница', 'пят', 'пт', '05', '5')):
|
|
547
|
+
result=5
|
|
548
|
+
elif value.startswith(('saturday', 'sat', 'sa', 'суббота', 'суб', 'сб', '06', '6')):
|
|
549
|
+
result=6
|
|
550
|
+
elif value.startswith(('sunday', 'sun', 'su', 'воскресенье', 'вос', 'вс', '07', '7')):
|
|
551
|
+
result=7
|
|
552
|
+
else:
|
|
553
|
+
raise ValueError('The entered day of the week does not exist!!!')
|
|
554
|
+
if start_zero==True and value in numweek_list:
|
|
555
|
+
result+=1
|
|
556
|
+
if start_sunday==True:
|
|
557
|
+
result-=1
|
|
558
|
+
if result==0:
|
|
559
|
+
result=7
|
|
560
|
+
return result
|
|
561
|
+
|
|
562
|
+
def distributor(s):
|
|
563
|
+
s=[i for i in s if i!=' ']
|
|
564
|
+
result=[]
|
|
565
|
+
elem=[]
|
|
566
|
+
isnum=True
|
|
567
|
+
for i in s:
|
|
568
|
+
if i.isdigit() and isnum==True:
|
|
569
|
+
elem.append(i)
|
|
570
|
+
elif (i.isalpha() or i==',') and isnum==False:
|
|
571
|
+
elem.append(i)
|
|
572
|
+
else:
|
|
573
|
+
ready_elem=''.join(elem)
|
|
574
|
+
if ready_elem.endswith('and'):
|
|
575
|
+
ready_elem=ready_elem[:-3]
|
|
576
|
+
elif ready_elem.endswith(',') or ready_elem.endswith('и'):
|
|
577
|
+
ready_elem=ready_elem[:-1]
|
|
578
|
+
result.append(ready_elem)
|
|
579
|
+
elem=[i]
|
|
580
|
+
isnum=not isnum
|
|
581
|
+
result.append(''.join(elem))
|
|
582
|
+
result=[i.strip() for i in result if i!='']
|
|
583
|
+
return result
|
|
584
|
+
|
|
585
|
+
def work_timezone1(value, to_tz, from_tz):
|
|
586
|
+
if to_tz in timezones:
|
|
587
|
+
if from_tz is None:
|
|
588
|
+
from_tz=datetime.now().astimezone().tzinfo
|
|
589
|
+
else:
|
|
590
|
+
from_tz=timezones[from_tz.lower()]
|
|
591
|
+
to_tz=timezones[to_tz.lower()]
|
|
592
|
+
value=value.tz_localize(from_tz).tz_convert(to_tz)
|
|
593
|
+
elif from_tz in timezones:
|
|
594
|
+
from_tz=timezones[from_tz.lower()]
|
|
595
|
+
value=value.tz_localize(from_tz)
|
|
596
|
+
return value
|
|
597
|
+
|
|
598
|
+
def work_timezone2(value, keyword, to_tz, from_tz):
|
|
599
|
+
if to_tz not in timezones and from_tz not in timezones:
|
|
600
|
+
return value.strftime('%X') if keyword=='time' else value.strftime('%Y-%m-%d %X')
|
|
601
|
+
value=value.strftime('%X %z') if keyword=='time' else value.strftime('%Y-%m-%d %X %z')
|
|
602
|
+
value=list(value)
|
|
603
|
+
value.insert(-2, ':')
|
|
604
|
+
value=''.join(value)
|
|
605
|
+
return value.strip()
|
|
606
|
+
|
|
607
|
+
dt_list={'yesterday', 'the day before yesterday', 'tomorrow', 'the day after tomorrow', 'today', 'now', 'ago',
|
|
608
|
+
'in', 'half an hour ago', 'in half an hour', 'an hour and a half ago', 'in an hour and a half', 'next',
|
|
609
|
+
'last', 'this', 'вчера', 'позавчера', 'завтра', 'послезавтра', 'сегодня', 'сейчас', 'назад', 'через',
|
|
610
|
+
'полчаса назад', 'через полчаса', 'полтора часа назад', 'через полтора часа', 'следующ', 'прошл',
|
|
611
|
+
'предыдущ', 'эт'}
|
|
612
|
+
|
|
613
|
+
def relative_datetime(value, keyword, *, current_date='now', current_time='now', current_datetime='now',
|
|
614
|
+
from_tz=None, to_tz=None):
|
|
615
|
+
value=value.lower()
|
|
616
|
+
if keyword=='date':
|
|
617
|
+
current=Timestamp(current_date)
|
|
618
|
+
elif keyword=='time':
|
|
619
|
+
current=work_timezone1(Timestamp(current_time), to_tz, from_tz)
|
|
620
|
+
else:
|
|
621
|
+
current=work_timezone1(Timestamp(current_datetime), to_tz, from_tz)
|
|
622
|
+
if value in ('yesterday', 'вчера'):
|
|
623
|
+
result=current-DateOffset(days=1)
|
|
624
|
+
elif value in ('the day before yesterday', 'позавчера'):
|
|
625
|
+
result=current-DateOffset(days=2)
|
|
626
|
+
elif value in ('tomorrow', 'завтра'):
|
|
627
|
+
result=current+DateOffset(days=1)
|
|
628
|
+
elif value in ('the day after tomorrow', 'послезавтра'):
|
|
629
|
+
result=current+DateOffset(days=2)
|
|
630
|
+
elif value in ('today', 'now', 'сегодня', 'сейчас'):
|
|
631
|
+
result=current
|
|
632
|
+
elif value in ('half an hour ago', 'полчаса назад'):
|
|
633
|
+
result=current-DateOffset(minutes=30)
|
|
634
|
+
elif value in ('an hour and a half ago', 'полтора часа назад'):
|
|
635
|
+
result=current-DateOffset(minutes=90)
|
|
636
|
+
elif value in ('in half an hour', 'через полчаса'):
|
|
637
|
+
result=current+DateOffset(minutes=30)
|
|
638
|
+
elif value in ('in an hour and a half', 'через полтора часа'):
|
|
639
|
+
result=current+DateOffset(minutes=90)
|
|
640
|
+
else:
|
|
641
|
+
value=value.split()
|
|
642
|
+
value=[i for i in value if i not in {'в', 'на', 'к', 'со'}]
|
|
643
|
+
if value[0].startswith(('next', 'следующ')):
|
|
644
|
+
if value[-1].startswith(('year', 'год')):
|
|
645
|
+
result=current+DateOffset(years=1)
|
|
646
|
+
elif value[-1].startswith(('month', 'месяц')):
|
|
647
|
+
result=current+DateOffset(months=1)
|
|
648
|
+
elif value[-1].startswith(('week', 'недел')):
|
|
649
|
+
result=current+DateOffset(weeks=1)
|
|
650
|
+
else:
|
|
651
|
+
current_day=current.dayofweek+1
|
|
652
|
+
next_day=take_weekday(value[-1], False, False)
|
|
653
|
+
result=current+DateOffset(days=7+(next_day-current_day))
|
|
654
|
+
elif value[0].startswith(('last', 'прошл', 'предыдущ')):
|
|
655
|
+
if value[-1].startswith(('year', 'год')):
|
|
656
|
+
result=current-DateOffset(years=1)
|
|
657
|
+
elif value[-1].startswith(('month', 'месяц')):
|
|
658
|
+
result=current-DateOffset(months=1)
|
|
659
|
+
elif value[-1].startswith(('week', 'недел')):
|
|
660
|
+
result=current-DateOffset(weeks=1)
|
|
661
|
+
else:
|
|
662
|
+
current_day=current.dayofweek+1
|
|
663
|
+
next_day=take_weekday(value[-1], False, False)
|
|
664
|
+
result=current-DateOffset(days=7-(next_day-current_day))
|
|
665
|
+
elif value[0].startswith(('this', 'эт')):
|
|
666
|
+
if value[-1].startswith(('year', 'month', 'week', 'год', 'месяц', 'недел')):
|
|
667
|
+
result=current
|
|
668
|
+
else:
|
|
669
|
+
current_day=current.dayofweek+1
|
|
670
|
+
next_day=take_weekday(value[-1], False, False)
|
|
671
|
+
result=current-DateOffset(days=current_day-next_day)
|
|
672
|
+
else:
|
|
673
|
+
if value[-1] in ('ago', 'назад'):
|
|
674
|
+
if value[0] in ('a', 'an'):
|
|
675
|
+
value[0]='1'
|
|
676
|
+
elif len(value)==2:
|
|
677
|
+
value.insert(0, '1')
|
|
678
|
+
word=''.join(value[:-1])
|
|
679
|
+
else:
|
|
680
|
+
if value[1] in ('a', 'an'):
|
|
681
|
+
value[1]='1'
|
|
682
|
+
elif len(value)==2:
|
|
683
|
+
value.insert(1, '1')
|
|
684
|
+
word=''.join(value[1:])
|
|
685
|
+
years, weeks, months, days, hours, minutes, seconds=0, 0, 0, 0, 0, 0, 0
|
|
686
|
+
distrub_list=distributor(word)
|
|
687
|
+
for i in range(0, len(distrub_list), 2):
|
|
688
|
+
if any(x==distrub_list[i+1] for x in ['day', 'days', 'день', 'дня', 'дней']):
|
|
689
|
+
days+=int(distrub_list[i])
|
|
690
|
+
if any(x==distrub_list[i+1] for x in ['week', 'weeks', 'неделю', 'недель', 'недели']):
|
|
691
|
+
weeks+=int(distrub_list[i])
|
|
692
|
+
if any(x==distrub_list[i+1] for x in ['month', 'months', 'месяц', 'месяца', 'месяцев']):
|
|
693
|
+
months+=int(distrub_list[i])
|
|
694
|
+
if any(x==distrub_list[i+1] for x in ['year', 'years', 'год', 'года', 'лет']):
|
|
695
|
+
years+=int(distrub_list[i])
|
|
696
|
+
if any(x==distrub_list[i+1] for x in ['h', 'hour', 'hours', 'ч', 'час', 'часа', 'часов']):
|
|
697
|
+
hours+=int(distrub_list[i])
|
|
698
|
+
if any(x==distrub_list[i+1] for x in ['m', 'min', 'minute', 'minutes', 'м', 'мин', 'минут', 'минуту']):
|
|
699
|
+
minutes+=int(distrub_list[i])
|
|
700
|
+
if any(x==distrub_list[i+1] for x in ['s', 'sec', 'second', 'seconds', 'с', 'сек', 'секунд', 'секунду']):
|
|
701
|
+
seconds+=int(distrub_list[i])
|
|
702
|
+
offset=DateOffset(years=years, weeks=weeks, months=months, days=days,
|
|
703
|
+
hours=hours, minutes=minutes, seconds=seconds)
|
|
704
|
+
if value[-1] in ('ago', 'назад'):
|
|
705
|
+
result=current-offset
|
|
706
|
+
elif value[0] in ('in', 'через'):
|
|
707
|
+
result=current+offset
|
|
708
|
+
if keyword=='date':
|
|
709
|
+
return result.strftime('%Y-%m-%d')
|
|
710
|
+
return work_timezone2(result, keyword, to_tz, from_tz)
|
|
711
|
+
|
|
712
|
+
def make_date(value, *, order='ymd', current_date='now', century=21, start_sunday=False, start_zero=False):
|
|
713
|
+
if isinstance(value, str):
|
|
714
|
+
keyword='date'
|
|
715
|
+
value=value.lower().strip()
|
|
716
|
+
if any(i in value for i in dt_list):
|
|
717
|
+
return relative_datetime(value, keyword, current_date=current_date)
|
|
718
|
+
lst=re.split(r'[-/.,: ]', value)
|
|
719
|
+
lst=[i.strip() for i in lst if i!='']
|
|
720
|
+
else:
|
|
721
|
+
lst=value
|
|
722
|
+
lst=lst[:len(order)]
|
|
723
|
+
if 'y' not in order:
|
|
724
|
+
current_year=Timestamp(current_date).year
|
|
725
|
+
lst.append(str(current_year))
|
|
726
|
+
year_idx=2
|
|
727
|
+
else:
|
|
728
|
+
year_idx=order.index('y')
|
|
729
|
+
if len(lst[year_idx])==2:
|
|
730
|
+
lst[year_idx]=f'{str(century-1)}{lst[year_idx]}'
|
|
731
|
+
elif len(lst[year_idx])<2:
|
|
732
|
+
raise ValueError('The year should not be less than 100!!!')
|
|
733
|
+
if 'n' in order and 'w' in order:
|
|
734
|
+
numweek_idx=order.index('n')
|
|
735
|
+
weekday_idx=order.index('w')
|
|
736
|
+
weekday_value=take_weekday(lst[weekday_idx], start_zero, start_sunday)
|
|
737
|
+
if lst[numweek_idx].startswith('w'):
|
|
738
|
+
lst[numweek_idx]=lst[numweek_idx][1:]
|
|
739
|
+
first_day_year=str(Timestamp(lst[year_idx]).dayofweek+1)
|
|
740
|
+
if (int(lst[year_idx])%4==0 and first_day_year in ('3', '4')) or first_day_year=='4':
|
|
741
|
+
max_numweek=53
|
|
742
|
+
else:
|
|
743
|
+
max_numweek=52
|
|
744
|
+
if 0<int(lst[numweek_idx])<=max_numweek:
|
|
745
|
+
result=f'{lst[year_idx]}-W{lst[numweek_idx]}-{weekday_value}'
|
|
746
|
+
return str(to_datetime(result, format='%G-W%V-%u').date())
|
|
747
|
+
raise ValueError('The week number must not exceed the maximum number of the specified year!!!')
|
|
748
|
+
else:
|
|
749
|
+
month_idx=order.index('m')
|
|
750
|
+
day_idx=order.index('d')
|
|
751
|
+
month_values=take_month(lst[month_idx].lower())
|
|
752
|
+
if int(lst[year_idx])%4==0 and month_values[0]==2:
|
|
753
|
+
month_values[1]+=1
|
|
754
|
+
lst[month_idx]=month_values[0]
|
|
755
|
+
if 0<int(lst[day_idx])<=month_values[1]:
|
|
756
|
+
return f'{lst[year_idx]}-{str(lst[month_idx]).zfill(2)}-{str(lst[day_idx]).zfill(2)}'
|
|
757
|
+
raise ValueError('A month cannot be more than 12!!!')
|
|
758
|
+
|
|
759
|
+
def make_time(value, *, order='HMS', current_time='now', from_tz=None, to_tz=None):
|
|
760
|
+
keyword='time'
|
|
761
|
+
if isinstance(value, str):
|
|
762
|
+
value=value.lower()
|
|
763
|
+
if any(i in value for i in dt_list):
|
|
764
|
+
return relative_datetime(value, keyword, current_time=current_time, from_tz=from_tz, to_tz=to_tz)
|
|
765
|
+
pattern=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])\s*|\s*[-/.,: ]\s*'
|
|
766
|
+
lst=re.split(pattern, value)
|
|
767
|
+
lst=[i.strip() for i in lst if i!='']
|
|
768
|
+
else:
|
|
769
|
+
lst=value.copy()
|
|
770
|
+
lst=[i.strip() for i in lst if i.strip() not in ['am', 'pm', 'a.m', 'p.m']]
|
|
771
|
+
order=order[:len(lst)]
|
|
772
|
+
if not any(i in {'H', 'M', 'S'} for i in order):
|
|
773
|
+
raise ValueError('Error!!!')
|
|
774
|
+
if 'H' not in order:
|
|
775
|
+
hour_value='00'
|
|
776
|
+
else:
|
|
777
|
+
hour_idx=order.index('H')
|
|
778
|
+
if 'pm' in value or 'p.m.' in value:
|
|
779
|
+
if lst[hour_idx]=='12':
|
|
780
|
+
lst[hour_idx]='12'
|
|
781
|
+
elif 0<=int(lst[hour_idx])<12:
|
|
782
|
+
lst[hour_idx]=str(int(lst[hour_idx].strip())+12)
|
|
783
|
+
if 'am' in value or 'a.m.' in value:
|
|
784
|
+
if lst[hour_idx]=='12':
|
|
785
|
+
lst[hour_idx]='00'
|
|
786
|
+
elif 12<int(lst[hour_idx])<=24:
|
|
787
|
+
lst[hour_idx]=str(int(lst[hour_idx].strip())-12)
|
|
788
|
+
if 0<=int(lst[hour_idx])<24:
|
|
789
|
+
hour_value=lst[hour_idx]
|
|
790
|
+
elif int(lst[hour_idx])==24:
|
|
791
|
+
hour_value='00'
|
|
792
|
+
else:
|
|
793
|
+
raise ValueError('Hours cannot be greater than 24 and less than 0!!!')
|
|
794
|
+
if 'M' not in order:
|
|
795
|
+
minute_value='00'
|
|
796
|
+
else:
|
|
797
|
+
minute_idx=order.index('M')
|
|
798
|
+
if 0<=int(lst[minute_idx])<60:
|
|
799
|
+
minute_value=lst[minute_idx]
|
|
800
|
+
elif int(lst[minute_idx])==60:
|
|
801
|
+
minute_value='00'
|
|
802
|
+
else:
|
|
803
|
+
raise ValueError('Minutes cannot be more than 60 and less than 0!!!')
|
|
804
|
+
if 'S' not in order:
|
|
805
|
+
second_value='00'
|
|
806
|
+
else:
|
|
807
|
+
second_idx=order.index('S')
|
|
808
|
+
if 0<=int(lst[second_idx])<60:
|
|
809
|
+
second_value=lst[second_idx]
|
|
810
|
+
elif int(lst[second_idx])==60:
|
|
811
|
+
second_value='00'
|
|
812
|
+
else:
|
|
813
|
+
raise ValueError('Seconds cannot be greater than 60 and less than 0!!!')
|
|
814
|
+
result=f'{hour_value.zfill(2)}:{minute_value.zfill(2)}:{second_value.zfill(2)}'
|
|
815
|
+
result=work_timezone1(Timestamp(result), to_tz, from_tz)
|
|
816
|
+
return work_timezone2(result, keyword, to_tz, from_tz)
|
|
817
|
+
|
|
818
|
+
def make_datetime(value, *, order_date='ymd', order_time='HMS', century=21, isfirsttime=False,
|
|
819
|
+
start_sunday=False, start_zero=False, current_datetime='now', from_tz=None, to_tz=None):
|
|
820
|
+
value=value.lower().strip()
|
|
821
|
+
if any(i in value for i in dt_list):
|
|
822
|
+
return relative_datetime(value, 'datetime', current_datetime=current_datetime, from_tz=from_tz, to_tz=to_tz)
|
|
823
|
+
pattern1=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])\s*|\s*[-/.,: ]\s*'
|
|
824
|
+
pattern2=r'\s*(?<![a-zA-Z])(?:a\.m|p\.m|am|pm)\.?(?![a-zA-Z])'
|
|
825
|
+
lst=re.split(pattern1, value)
|
|
826
|
+
lst=[i.strip() for i in lst if i!='']
|
|
827
|
+
special_symbol=re.findall(pattern2, value)[:1]
|
|
828
|
+
special_symbol=''.join(special_symbol).strip()
|
|
829
|
+
part1, part2='', ''
|
|
830
|
+
if isfirsttime is False:
|
|
831
|
+
part1=make_date(lst[:len(order_date)], order=order_date, century=century, start_sunday=start_sunday, start_zero=start_zero)
|
|
832
|
+
if lst[len(order_date):]!=[]:
|
|
833
|
+
part2=make_time(lst[len(order_date):]+[special_symbol], order=order_time)
|
|
834
|
+
else:
|
|
835
|
+
if lst[len(order_time):]!=[]:
|
|
836
|
+
part1=make_date(lst[len(order_time):], order=order_date, century=century, start_sunday=start_sunday, start_zero=start_zero)
|
|
837
|
+
part2=make_time(lst[:len(order_time)]+[special_symbol], order=order_time)
|
|
838
|
+
result=f'{part1} {part2}'.strip()
|
|
839
|
+
result=work_timezone1(Timestamp(result), to_tz, from_tz)
|
|
840
|
+
return work_timezone2(result, 'datetime', to_tz, from_tz)
|
|
841
|
+
|
|
842
|
+
def convert_units(num, value1=None, value2=None, auto=False, round_value=None):
|
|
843
|
+
if auto==True:
|
|
844
|
+
auto_num=distributor(num)[0]
|
|
845
|
+
idx=num.index(auto_num[-1])
|
|
846
|
+
value1=num[idx+1:]
|
|
847
|
+
num=int(auto_num)
|
|
848
|
+
if num<=0:
|
|
849
|
+
raise ValueError('The number must not be less than or equal to zero!!!')
|
|
850
|
+
if value2 is None:
|
|
851
|
+
value2=value1
|
|
852
|
+
value1, value2=value1.lower().strip(), value2.lower().strip()
|
|
853
|
+
for i in units:
|
|
854
|
+
if value1 in units[i][0] and value2 in units[i][0]:
|
|
855
|
+
dct1, dct2=units[i][0], units[i][1]
|
|
856
|
+
break
|
|
857
|
+
else:
|
|
858
|
+
raise ValueError('You have entered invalid units of measurement, or the pair of units is incompatible!!!')
|
|
859
|
+
v1=dct1[value1]
|
|
860
|
+
v2=dct1[value2]
|
|
861
|
+
if v1<v2:
|
|
862
|
+
for i in range(v1, v2):
|
|
863
|
+
num/=dct2[i]
|
|
864
|
+
elif v1==v2:
|
|
865
|
+
return num
|
|
866
|
+
else:
|
|
867
|
+
for i in range(v1-1, v2-1, -1):
|
|
868
|
+
num*=dct2[i]
|
|
869
|
+
return num if round_value is None else super_round(num, round_value)
|
|
870
|
+
|
|
871
|
+
def freecopy(obj, memo=None):
|
|
872
|
+
if memo is None:
|
|
873
|
+
memo={}
|
|
874
|
+
if id(obj) in memo:
|
|
875
|
+
return memo[id(obj)]
|
|
876
|
+
if isinstance(obj, list):
|
|
877
|
+
result=[]
|
|
878
|
+
memo[id(obj)]=result
|
|
879
|
+
for i in obj:
|
|
880
|
+
result.append(freecopy(i, memo))
|
|
881
|
+
return result
|
|
882
|
+
elif isinstance(obj, tuple):
|
|
883
|
+
result=tuple(freecopy(i, memo) for i in obj)
|
|
884
|
+
memo[id(obj)]=result
|
|
885
|
+
return result
|
|
886
|
+
elif isinstance(obj, set):
|
|
887
|
+
result=set()
|
|
888
|
+
memo[id(obj)]=result
|
|
889
|
+
for i in obj:
|
|
890
|
+
result.add(freecopy(i, memo))
|
|
891
|
+
return result
|
|
892
|
+
elif isinstance(obj, dict):
|
|
893
|
+
result={}
|
|
894
|
+
memo[id(obj)]=result
|
|
895
|
+
for i, j in obj.items():
|
|
896
|
+
result[freecopy(i, memo)]=freecopy(j, memo)
|
|
897
|
+
return result
|
|
898
|
+
elif isinstance(obj, deque):
|
|
899
|
+
result=deque()
|
|
900
|
+
memo[id(obj)]=result
|
|
901
|
+
for i in obj:
|
|
902
|
+
result.apppend(freecopy(i, memo))
|
|
903
|
+
return result
|
|
904
|
+
return obj
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|