derafu-support 1.0.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.
- derafu_support-1.0.0/LICENSE +21 -0
- derafu_support-1.0.0/PKG-INFO +70 -0
- derafu_support-1.0.0/README.md +44 -0
- derafu_support-1.0.0/pyproject.toml +156 -0
- derafu_support-1.0.0/setup.cfg +4 -0
- derafu_support-1.0.0/src/derafu_support/__init__.py +6 -0
- derafu_support-1.0.0/src/derafu_support/dates.py +281 -0
- derafu_support-1.0.0/src/derafu_support/dictionary_file_operations.py +74 -0
- derafu_support-1.0.0/src/derafu_support/dictionary_merge.py +47 -0
- derafu_support-1.0.0/src/derafu_support/encoding.py +24 -0
- derafu_support-1.0.0/src/derafu_support/exceptions.py +21 -0
- derafu_support-1.0.0/src/derafu_support/gravatar.py +29 -0
- derafu_support-1.0.0/src/derafu_support/is_empty.py +124 -0
- derafu_support-1.0.0/src/derafu_support/is_set.py +94 -0
- derafu_support-1.0.0/src/derafu_support/log.py +372 -0
- derafu_support-1.0.0/src/derafu_support/number_format.py +56 -0
- derafu_support-1.0.0/src/derafu_support/py.typed +0 -0
- derafu_support-1.0.0/src/derafu_support.egg-info/PKG-INFO +70 -0
- derafu_support-1.0.0/src/derafu_support.egg-info/SOURCES.txt +23 -0
- derafu_support-1.0.0/src/derafu_support.egg-info/dependency_links.txt +1 -0
- derafu_support-1.0.0/src/derafu_support.egg-info/requires.txt +1 -0
- derafu_support-1.0.0/src/derafu_support.egg-info/top_level.txt +1 -0
- derafu_support-1.0.0/tests/test_dates.py +120 -0
- derafu_support-1.0.0/tests/test_dictionaries.py +163 -0
- derafu_support-1.0.0/tests/test_misc.py +108 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Esteban De La Fuente Rubio / Derafu <https://www.derafu.org>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: derafu-support
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: General-purpose Python utilities (dates, dictionaries, numbers and logging).
|
|
5
|
+
Author: Derafu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/derafu/support-python
|
|
8
|
+
Project-URL: Issues, https://github.com/derafu/support-python/issues
|
|
9
|
+
Keywords: utilities,dates,dictionary,logging,formatting
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Topic :: Utilities
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.13
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: Babel>=2.19
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# derafu-support
|
|
28
|
+
|
|
29
|
+
General-purpose Python utilities. The library does not depend on Django.
|
|
30
|
+
|
|
31
|
+
Requires Python 3.13 or newer; tested on 3.13, 3.14 and 3.15.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
pip install derafu-support
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Contents
|
|
40
|
+
|
|
41
|
+
| Module | Contents |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `dates` | YYYYMM periods (`period_current`, `period_previous`, `period_next`, `period_range`, `period_first_day`, `period_last_day`, `period_valid`), dates (`date_normalize`, `date_add_days`, `date_count_days`) and Spanish month names (`month_from_string`, `month_from_index`, `month_from_number`) |
|
|
44
|
+
| `dictionary_merge` | `merge()`: recursive merge of dictionaries |
|
|
45
|
+
| `dictionary_file_operations` | `dict_save_to_json()`, `dict_save_to_csv()` and `dict_load_from_csv()` |
|
|
46
|
+
| `is_empty` / `is_set` | Checks for empty values and defined keys |
|
|
47
|
+
| `exceptions` | `NotIndexableError`, raised by both `is_empty()` and `is_set()` |
|
|
48
|
+
| `log` | `MemoryLogging`: in-memory log that records the caller |
|
|
49
|
+
| `number_format` | `format_number()`: locale-aware thousands and decimal separators |
|
|
50
|
+
| `gravatar` | `email_md5()` and `gravatar_url()` |
|
|
51
|
+
| `encoding` | `base64_decode()` with optional padding |
|
|
52
|
+
|
|
53
|
+
Example: `from derafu_support.dates import period_current`.
|
|
54
|
+
|
|
55
|
+
The dictionary selector (`selector()`) lives in the
|
|
56
|
+
[derafu-selector](https://github.com/derafu/selector-python) library.
|
|
57
|
+
|
|
58
|
+
## Development
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
make install-dev PYTHON=python3.15 # creates venv/ with the library and tools
|
|
62
|
+
make check # ruff, mypy, pyright and pytest
|
|
63
|
+
make build # builds dist/ and checks it with twine
|
|
64
|
+
make upload # builds dist/ and publishes it on PyPI
|
|
65
|
+
make docs # builds the Sphinx docs in docs/_build/html
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
MIT. See [LICENSE](https://github.com/derafu/support-python/blob/main/LICENSE).
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# derafu-support
|
|
2
|
+
|
|
3
|
+
General-purpose Python utilities. The library does not depend on Django.
|
|
4
|
+
|
|
5
|
+
Requires Python 3.13 or newer; tested on 3.13, 3.14 and 3.15.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install derafu-support
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Contents
|
|
14
|
+
|
|
15
|
+
| Module | Contents |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `dates` | YYYYMM periods (`period_current`, `period_previous`, `period_next`, `period_range`, `period_first_day`, `period_last_day`, `period_valid`), dates (`date_normalize`, `date_add_days`, `date_count_days`) and Spanish month names (`month_from_string`, `month_from_index`, `month_from_number`) |
|
|
18
|
+
| `dictionary_merge` | `merge()`: recursive merge of dictionaries |
|
|
19
|
+
| `dictionary_file_operations` | `dict_save_to_json()`, `dict_save_to_csv()` and `dict_load_from_csv()` |
|
|
20
|
+
| `is_empty` / `is_set` | Checks for empty values and defined keys |
|
|
21
|
+
| `exceptions` | `NotIndexableError`, raised by both `is_empty()` and `is_set()` |
|
|
22
|
+
| `log` | `MemoryLogging`: in-memory log that records the caller |
|
|
23
|
+
| `number_format` | `format_number()`: locale-aware thousands and decimal separators |
|
|
24
|
+
| `gravatar` | `email_md5()` and `gravatar_url()` |
|
|
25
|
+
| `encoding` | `base64_decode()` with optional padding |
|
|
26
|
+
|
|
27
|
+
Example: `from derafu_support.dates import period_current`.
|
|
28
|
+
|
|
29
|
+
The dictionary selector (`selector()`) lives in the
|
|
30
|
+
[derafu-selector](https://github.com/derafu/selector-python) library.
|
|
31
|
+
|
|
32
|
+
## Development
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
make install-dev PYTHON=python3.15 # creates venv/ with the library and tools
|
|
36
|
+
make check # ruff, mypy, pyright and pytest
|
|
37
|
+
make build # builds dist/ and checks it with twine
|
|
38
|
+
make upload # builds dist/ and publishes it on PyPI
|
|
39
|
+
make docs # builds the Sphinx docs in docs/_build/html
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## License
|
|
43
|
+
|
|
44
|
+
MIT. See [LICENSE](https://github.com/derafu/support-python/blob/main/LICENSE).
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=84.2.1"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "derafu-support"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "General-purpose Python utilities (dates, dictionaries, numbers and logging)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.13"
|
|
13
|
+
authors = [{ name = "Derafu" }]
|
|
14
|
+
keywords = ["utilities", "dates", "dictionary", "logging", "formatting"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Programming Language :: Python :: 3.15",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Topic :: Utilities",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"Babel>=2.19", # format_number()
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Repository = "https://github.com/derafu/support-python"
|
|
34
|
+
Issues = "https://github.com/derafu/support-python/issues"
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
# Documentation tools: `pip install --group docs`
|
|
38
|
+
docs = [
|
|
39
|
+
"sphinx==9.2.0",
|
|
40
|
+
"sphinx-rtd-theme==3.1.0",
|
|
41
|
+
# docutils 0.22 is the newest that sphinx-rtd-theme accepts (<0.23)
|
|
42
|
+
"docutils==0.22.4",
|
|
43
|
+
"types-docutils==0.22.3.20260724", # types for docs/conf.py
|
|
44
|
+
]
|
|
45
|
+
# Development tools (lint, types, tests, packaging and documentation):
|
|
46
|
+
# `pip install --group dev`
|
|
47
|
+
dev = [
|
|
48
|
+
{ include-group = "docs" },
|
|
49
|
+
# runtime dependency at its newest version, to test against it
|
|
50
|
+
"Babel==2.19.0",
|
|
51
|
+
# lint, types and tests
|
|
52
|
+
"mypy==2.4.1",
|
|
53
|
+
"pyright==1.1.414",
|
|
54
|
+
"pytest==9.2.0",
|
|
55
|
+
"ruff==0.17.6",
|
|
56
|
+
# build and check the distributions uploaded to PyPI
|
|
57
|
+
"build==1.6.1",
|
|
58
|
+
"twine==7.0.0",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.setuptools.packages.find]
|
|
62
|
+
where = ["src"]
|
|
63
|
+
|
|
64
|
+
[tool.setuptools.package-data]
|
|
65
|
+
derafu_support = ["py.typed"]
|
|
66
|
+
|
|
67
|
+
[tool.ruff]
|
|
68
|
+
include = ["**/*.py", "**/*.pyi"]
|
|
69
|
+
exclude = [".git", "__pycache__", "build", "dist", "venv"]
|
|
70
|
+
line-length = 79
|
|
71
|
+
# no target-version: Ruff takes the minimum version from requires-python, so
|
|
72
|
+
# it never suggests syntax that the oldest supported Python cannot run
|
|
73
|
+
respect-gitignore = true
|
|
74
|
+
fix = false
|
|
75
|
+
|
|
76
|
+
[tool.ruff.lint]
|
|
77
|
+
select = [
|
|
78
|
+
"D", # pydocstyle: docstrings
|
|
79
|
+
"F", # Pyflakes: code errors
|
|
80
|
+
"E", # pycodestyle: style
|
|
81
|
+
"W", # pycodestyle: warnings
|
|
82
|
+
"I", # isort: import order
|
|
83
|
+
"UP", # pyupgrade: modern syntax
|
|
84
|
+
"N", # pep8-naming: names
|
|
85
|
+
"B", # bugbear: common bug patterns
|
|
86
|
+
"A", # flake8-builtins: do not shadow builtins or stdlib names
|
|
87
|
+
"C90", # mccabe: complexity
|
|
88
|
+
"ANN", # flake8-annotations: type annotations
|
|
89
|
+
"ARG", # unused arguments
|
|
90
|
+
"DTZ", # timezone-aware dates
|
|
91
|
+
"TRY", # tryceratops: exception handling
|
|
92
|
+
"SLF", # private member access
|
|
93
|
+
"ERA", # commented-out code
|
|
94
|
+
"PL", # pylint
|
|
95
|
+
"PT", # pytest style
|
|
96
|
+
"SIM", # simplifications
|
|
97
|
+
"RET", # returns
|
|
98
|
+
"C4", # comprehensions
|
|
99
|
+
"PTH", # pathlib instead of os.path
|
|
100
|
+
"PIE", # miscellaneous
|
|
101
|
+
"RSE", # raise
|
|
102
|
+
"PERF", # performance
|
|
103
|
+
"FURB", # refurb: modern idioms
|
|
104
|
+
"PGH", # pygrep-hooks (forbids blanket ignores)
|
|
105
|
+
"RUF", # Ruff-specific rules
|
|
106
|
+
"FBT", # flake8-boolean-trap: boolean flags are keyword-only
|
|
107
|
+
"INP", # flake8-no-pep420: no implicit namespace packages
|
|
108
|
+
"PYI", # flake8-pyi: type stubs
|
|
109
|
+
# preview rules, enabled one by one (explicit-preview-rules)
|
|
110
|
+
"D421", # property docstrings do not start with a verb
|
|
111
|
+
"RUF052", # local dummy variables (_name) are not used
|
|
112
|
+
]
|
|
113
|
+
ignore = [
|
|
114
|
+
# Docstring style: Ruff cannot enforce both rules of each pair.
|
|
115
|
+
# - D211 is dropped in favor of D203 (blank line before a class
|
|
116
|
+
# docstring). The project does not use `ruff format`, which would
|
|
117
|
+
# remove that line.
|
|
118
|
+
# - D212 is dropped in favor of D213 (summary on the second line), the
|
|
119
|
+
# docstring style of the library.
|
|
120
|
+
"D211",
|
|
121
|
+
"D212",
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
# preview rules only apply when listed by code in `select`
|
|
125
|
+
preview = true
|
|
126
|
+
explicit-preview-rules = true
|
|
127
|
+
|
|
128
|
+
[tool.ruff.lint.mccabe]
|
|
129
|
+
max-complexity = 25
|
|
130
|
+
|
|
131
|
+
[tool.ruff.lint.pylint]
|
|
132
|
+
max-args = 10
|
|
133
|
+
max-branches = 25
|
|
134
|
+
max-statements = 60
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
[tool.mypy]
|
|
138
|
+
# no python_version: mypy checks against the running interpreter, so each CI
|
|
139
|
+
# job (3.13, 3.14 and 3.15) checks its own version
|
|
140
|
+
strict = true
|
|
141
|
+
# methods that override a parent method must use @override
|
|
142
|
+
enable_error_code = ["explicit-override"]
|
|
143
|
+
files = ["src", "tests", "docs"]
|
|
144
|
+
|
|
145
|
+
[tool.pyright]
|
|
146
|
+
include = ["src", "tests", "docs"]
|
|
147
|
+
exclude = ["**/__pycache__", "build", "dist", "venv"]
|
|
148
|
+
# no pythonVersion: `make typecheck` passes the venv interpreter
|
|
149
|
+
# (--pythonpath), so pyright checks against its version
|
|
150
|
+
typeCheckingMode = "strict"
|
|
151
|
+
venvPath = "."
|
|
152
|
+
venv = "venv"
|
|
153
|
+
|
|
154
|
+
[tool.pytest.ini_options]
|
|
155
|
+
testpaths = ["tests"]
|
|
156
|
+
addopts = "-ra --strict-markers --strict-config"
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions for tax periods (YYYYMM), dates and month names.
|
|
3
|
+
|
|
4
|
+
A period is an integer with the year and month (``202611``). Dates are
|
|
5
|
+
received and returned as ``YYYY-MM-DD`` strings.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from datetime import UTC, date, datetime, timedelta
|
|
9
|
+
|
|
10
|
+
# length of a monthly period (YYYYMM) and of a yearly one (YYYY)
|
|
11
|
+
_MONTHLY_PERIOD_LENGTH = 6
|
|
12
|
+
_YEARLY_PERIOD_LENGTH = 4
|
|
13
|
+
# month left after subtracting or adding a month without adjusting the year
|
|
14
|
+
_MONTH_BEFORE_JANUARY = 0
|
|
15
|
+
_MONTH_AFTER_DECEMBER = 13
|
|
16
|
+
# months in a year
|
|
17
|
+
_MONTHS_PER_YEAR = 12
|
|
18
|
+
# parts of a date and time with minutes ("31/12/2026 10:30")
|
|
19
|
+
_DATE_TIME_PARTS = 2
|
|
20
|
+
_HOUR_MINUTES_LENGTH = 5
|
|
21
|
+
|
|
22
|
+
_MONTH_NAMES = (
|
|
23
|
+
'enero',
|
|
24
|
+
'febrero',
|
|
25
|
+
'marzo',
|
|
26
|
+
'abril',
|
|
27
|
+
'mayo',
|
|
28
|
+
'junio',
|
|
29
|
+
'julio',
|
|
30
|
+
'agosto',
|
|
31
|
+
'septiembre',
|
|
32
|
+
'octubre',
|
|
33
|
+
'noviembre',
|
|
34
|
+
'diciembre',
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _today() -> date:
|
|
39
|
+
"""
|
|
40
|
+
Return today's date in the system's local time zone.
|
|
41
|
+
|
|
42
|
+
:return: Today's date.
|
|
43
|
+
:rtype: date
|
|
44
|
+
"""
|
|
45
|
+
return datetime.now().astimezone().date()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def period_current() -> int:
|
|
49
|
+
"""
|
|
50
|
+
Return the current period (YYYYMM).
|
|
51
|
+
|
|
52
|
+
:return: Current period.
|
|
53
|
+
:rtype: int
|
|
54
|
+
"""
|
|
55
|
+
return int(_today().strftime('%Y%m'))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def period_previous(period: int | None = None) -> int:
|
|
59
|
+
"""
|
|
60
|
+
Return the period before the given one.
|
|
61
|
+
|
|
62
|
+
:param period: Period (YYYYMM). If not given, the current one is used.
|
|
63
|
+
:return: Previous period; January goes to December of the previous year.
|
|
64
|
+
:rtype: int
|
|
65
|
+
"""
|
|
66
|
+
if period is None:
|
|
67
|
+
period = period_current()
|
|
68
|
+
previous_period = period - 1
|
|
69
|
+
if (
|
|
70
|
+
len(str(period)) == _MONTHLY_PERIOD_LENGTH
|
|
71
|
+
and int(str(previous_period)[4:]) == _MONTH_BEFORE_JANUARY
|
|
72
|
+
):
|
|
73
|
+
previous_period = previous_period - 100 + _MONTHS_PER_YEAR
|
|
74
|
+
return previous_period
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def period_next(period: int | None = None) -> int:
|
|
78
|
+
"""
|
|
79
|
+
Return the period after the given one.
|
|
80
|
+
|
|
81
|
+
:param period: Period (YYYYMM). If not given, the current one is used.
|
|
82
|
+
:return: Next period; December goes to January of the next year.
|
|
83
|
+
:rtype: int
|
|
84
|
+
"""
|
|
85
|
+
if period is None:
|
|
86
|
+
period = period_current()
|
|
87
|
+
next_period = period + 1
|
|
88
|
+
if (
|
|
89
|
+
len(str(period)) == _MONTHLY_PERIOD_LENGTH
|
|
90
|
+
and int(str(next_period)[4:]) == _MONTH_AFTER_DECEMBER
|
|
91
|
+
):
|
|
92
|
+
next_period = next_period + 100 - _MONTHS_PER_YEAR
|
|
93
|
+
return next_period
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def period_range(period_from: int, period_to: int | None = None) -> list[int]:
|
|
97
|
+
"""
|
|
98
|
+
Return the periods between two periods, both included.
|
|
99
|
+
|
|
100
|
+
:param period_from: First period (YYYYMM).
|
|
101
|
+
:param period_to: Last period. If not given, the current one is used.
|
|
102
|
+
:return: Periods in order; empty if the first is after the last.
|
|
103
|
+
:rtype: list[int]
|
|
104
|
+
"""
|
|
105
|
+
if period_to is None:
|
|
106
|
+
period_to = period_current()
|
|
107
|
+
periods: list[int] = []
|
|
108
|
+
period = period_from
|
|
109
|
+
while period <= period_to:
|
|
110
|
+
periods.append(period)
|
|
111
|
+
period = period_next(period)
|
|
112
|
+
return periods
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def period_first_day(period: int) -> str:
|
|
116
|
+
"""
|
|
117
|
+
Return the first day of a period.
|
|
118
|
+
|
|
119
|
+
:param period: Period (YYYYMM).
|
|
120
|
+
:return: Date ``YYYY-MM-01``.
|
|
121
|
+
:rtype: str
|
|
122
|
+
"""
|
|
123
|
+
return str(period)[0:4] + '-' + str(period)[4:] + '-01'
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def period_last_day(period: int) -> str:
|
|
127
|
+
"""
|
|
128
|
+
Return the last day of a period.
|
|
129
|
+
|
|
130
|
+
:param period: Period (YYYYMM).
|
|
131
|
+
:return: Date ``YYYY-MM-DD`` of the last day of the month.
|
|
132
|
+
:rtype: str
|
|
133
|
+
"""
|
|
134
|
+
first_day_next_period = date.fromisoformat(
|
|
135
|
+
period_first_day(period_next(period))
|
|
136
|
+
)
|
|
137
|
+
return (first_day_next_period - timedelta(days=1)).isoformat()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def period_valid(
|
|
141
|
+
period: int | str, year_from: int = 2000, year_to: int = 2100
|
|
142
|
+
) -> bool:
|
|
143
|
+
"""
|
|
144
|
+
Tell whether a period (YYYYMM) or a year (YYYY) is valid.
|
|
145
|
+
|
|
146
|
+
:param period: Period or year, as a number or a string.
|
|
147
|
+
:param year_from: First accepted year.
|
|
148
|
+
:param year_to: Last accepted year.
|
|
149
|
+
:return: True if it is a 4 or 6 digit number with a valid year (and
|
|
150
|
+
month).
|
|
151
|
+
:rtype: bool
|
|
152
|
+
"""
|
|
153
|
+
try:
|
|
154
|
+
int(period)
|
|
155
|
+
except ValueError:
|
|
156
|
+
return False
|
|
157
|
+
period = str(period)
|
|
158
|
+
n_period = len(period)
|
|
159
|
+
if n_period == _YEARLY_PERIOD_LENGTH:
|
|
160
|
+
return year_from <= int(period) <= year_to
|
|
161
|
+
if n_period == _MONTHLY_PERIOD_LENGTH:
|
|
162
|
+
year = int(period[0:4])
|
|
163
|
+
month = int(period[4:])
|
|
164
|
+
return year_from <= year <= year_to and 1 <= month <= _MONTHS_PER_YEAR
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def date_normalize(
|
|
169
|
+
date: str, format_from: str | None = None, format_to: str | None = None
|
|
170
|
+
) -> str:
|
|
171
|
+
"""
|
|
172
|
+
Change the format of a date (by default, from DD/MM/YYYY to YYYY-MM-DD).
|
|
173
|
+
|
|
174
|
+
Without formats, ``DD/MM/YYYY``, ``DD/MM/YYYY HH:MM`` and
|
|
175
|
+
``DD/MM/YYYY HH:MM:SS`` are recognized, and returned as ``YYYY-MM-DD``,
|
|
176
|
+
``YYYY-MM-DD HH:MM`` and ``YYYY-MM-DD HH:MM:SS``.
|
|
177
|
+
|
|
178
|
+
:param date: Date as a string.
|
|
179
|
+
:param format_from: Input format (``strptime``).
|
|
180
|
+
:param format_to: Output format (``strftime``).
|
|
181
|
+
:return: Date in the output format.
|
|
182
|
+
:rtype: str
|
|
183
|
+
:raises ValueError: If the date does not match the input format.
|
|
184
|
+
:raises TypeError: If ``format_from`` is given but ``format_to`` is not.
|
|
185
|
+
"""
|
|
186
|
+
if format_from is None:
|
|
187
|
+
aux = date.split(' ')
|
|
188
|
+
if len(aux) == _DATE_TIME_PARTS:
|
|
189
|
+
if len(aux[1]) == _HOUR_MINUTES_LENGTH:
|
|
190
|
+
format_from = '%d/%m/%Y %H:%M'
|
|
191
|
+
format_to = '%Y-%m-%d %H:%M'
|
|
192
|
+
else:
|
|
193
|
+
format_from = '%d/%m/%Y %H:%M:%S'
|
|
194
|
+
format_to = '%Y-%m-%d %H:%M:%S'
|
|
195
|
+
else:
|
|
196
|
+
format_from = '%d/%m/%Y'
|
|
197
|
+
format_to = '%Y-%m-%d'
|
|
198
|
+
# the time zone (UTC) only avoids a naive datetime: it does not change
|
|
199
|
+
# the output text unless format_to asks for the zone (%z or %Z)
|
|
200
|
+
date_obj = datetime.strptime(date, format_from).replace(tzinfo=UTC)
|
|
201
|
+
if format_to is None:
|
|
202
|
+
# format_from without format_to: same as datetime.strftime(None)
|
|
203
|
+
msg = 'strftime() argument 1 must be str, not None'
|
|
204
|
+
raise TypeError(msg)
|
|
205
|
+
return date_obj.strftime(format_to)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def date_add_days(days: int, from_date: str | None = None) -> str:
|
|
209
|
+
"""
|
|
210
|
+
Add (or subtract) days to a date.
|
|
211
|
+
|
|
212
|
+
:param days: Days to add; if negative, they are subtracted.
|
|
213
|
+
:param from_date: Date ``YYYY-MM-DD``. If not given, today is used.
|
|
214
|
+
:return: Resulting date ``YYYY-MM-DD``.
|
|
215
|
+
:rtype: str
|
|
216
|
+
"""
|
|
217
|
+
if from_date is None:
|
|
218
|
+
from_date = _today().strftime('%Y-%m-%d')
|
|
219
|
+
y, m, d = from_date.split('-')
|
|
220
|
+
return str(date(int(y), int(m), int(d)) + timedelta(days=days))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def date_count_days(
|
|
224
|
+
date_from: str | date, date_to: str | date | None = None
|
|
225
|
+
) -> int:
|
|
226
|
+
"""
|
|
227
|
+
Count the days between two dates, regardless of their order.
|
|
228
|
+
|
|
229
|
+
Only the date part (``YYYY-MM-DD``) is used; the time is ignored.
|
|
230
|
+
|
|
231
|
+
:param date_from: Start date (or date and time).
|
|
232
|
+
:param date_to: End date (or date and time). If not given, today is
|
|
233
|
+
used.
|
|
234
|
+
:return: Days between both dates, always positive or zero.
|
|
235
|
+
:rtype: int
|
|
236
|
+
"""
|
|
237
|
+
if date_to is None:
|
|
238
|
+
date_to = _today().strftime('%Y-%m-%d')
|
|
239
|
+
y_from, m_from, d_from = str(date_from).split(' ')[0].split('-')
|
|
240
|
+
y_to, m_to, d_to = str(date_to).split(' ')[0].split('-')
|
|
241
|
+
delta = date(int(y_to), int(m_to), int(d_to)) - date(
|
|
242
|
+
int(y_from), int(m_from), int(d_from)
|
|
243
|
+
)
|
|
244
|
+
return abs(delta.days)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def month_from_string(month: str) -> str:
|
|
248
|
+
"""
|
|
249
|
+
Return the month number (``01`` to ``12``) from its name.
|
|
250
|
+
|
|
251
|
+
:param month: Month name in Spanish, case-insensitive.
|
|
252
|
+
:return: Two-digit month number, or the given text if it is not a month
|
|
253
|
+
name.
|
|
254
|
+
:rtype: str
|
|
255
|
+
"""
|
|
256
|
+
month_lower = month.lower()
|
|
257
|
+
if month_lower in _MONTH_NAMES:
|
|
258
|
+
return f'{_MONTH_NAMES.index(month_lower) + 1:02d}'
|
|
259
|
+
return month
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def month_from_index(index: int | str) -> str:
|
|
263
|
+
"""
|
|
264
|
+
Return the month name from its index (0 is January).
|
|
265
|
+
|
|
266
|
+
:param index: Month index; the remainder of dividing by 12 is used.
|
|
267
|
+
:return: Month name in Spanish and in lower case.
|
|
268
|
+
:rtype: str
|
|
269
|
+
"""
|
|
270
|
+
return _MONTH_NAMES[int(index) % _MONTHS_PER_YEAR]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def month_from_number(month: int | str) -> str:
|
|
274
|
+
"""
|
|
275
|
+
Return the month name from its number (1 is January).
|
|
276
|
+
|
|
277
|
+
:param month: Month number.
|
|
278
|
+
:return: Month name in Spanish and in lower case.
|
|
279
|
+
:rtype: str
|
|
280
|
+
"""
|
|
281
|
+
return month_from_index(int(month) - 1)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Read and write dictionaries from and to JSON and CSV files."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from os import PathLike
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
#: Path of a file: a string or a path-like object such as ``pathlib.Path``.
|
|
10
|
+
type StrPath = str | PathLike[str]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def dict_save_to_json(
|
|
14
|
+
json_filename: StrPath,
|
|
15
|
+
dict_data: object,
|
|
16
|
+
*,
|
|
17
|
+
sort_keys: bool = False,
|
|
18
|
+
indent: int = 4,
|
|
19
|
+
) -> None:
|
|
20
|
+
"""
|
|
21
|
+
Save data to a JSON file.
|
|
22
|
+
|
|
23
|
+
:param json_filename: File path (replaced if it exists).
|
|
24
|
+
:param dict_data: Data to save (dictionaries, lists, etc.).
|
|
25
|
+
:param sort_keys: Sort the dictionary keys (keyword-only).
|
|
26
|
+
:param indent: Indentation spaces (keyword-only).
|
|
27
|
+
"""
|
|
28
|
+
json_data = json.dumps(dict_data, sort_keys=sort_keys, indent=indent)
|
|
29
|
+
Path(json_filename).write_text(json_data, encoding='utf-8')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def dict_save_to_csv(
|
|
33
|
+
csv_filename: StrPath,
|
|
34
|
+
dict_data: Sequence[Mapping[str, object]],
|
|
35
|
+
delimiter: str = ';',
|
|
36
|
+
) -> None:
|
|
37
|
+
"""
|
|
38
|
+
Save a list of dictionaries to a CSV file.
|
|
39
|
+
|
|
40
|
+
The headers are the keys of the first dictionary. Without data, the file
|
|
41
|
+
is left empty.
|
|
42
|
+
|
|
43
|
+
:param csv_filename: File path (replaced if it exists).
|
|
44
|
+
:param dict_data: Rows, one per dictionary.
|
|
45
|
+
:param delimiter: Column separator.
|
|
46
|
+
"""
|
|
47
|
+
path = Path(csv_filename)
|
|
48
|
+
if len(dict_data) > 0:
|
|
49
|
+
keys = dict_data[0].keys()
|
|
50
|
+
with path.open('w', newline='', encoding='utf-8') as output_file:
|
|
51
|
+
dict_writer = csv.DictWriter(
|
|
52
|
+
output_file, fieldnames=list(keys), delimiter=delimiter
|
|
53
|
+
)
|
|
54
|
+
dict_writer.writeheader()
|
|
55
|
+
dict_writer.writerows(dict_data)
|
|
56
|
+
else:
|
|
57
|
+
path.write_text('', encoding='utf-8')
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def dict_load_from_csv(
|
|
61
|
+
csv_filename: StrPath, delimiter: str = ';'
|
|
62
|
+
) -> list[dict[str, str]]:
|
|
63
|
+
"""
|
|
64
|
+
Read a CSV file as a list of dictionaries.
|
|
65
|
+
|
|
66
|
+
The first row holds the headers, which are used as keys.
|
|
67
|
+
|
|
68
|
+
:param csv_filename: File path.
|
|
69
|
+
:param delimiter: Column separator.
|
|
70
|
+
:return: Rows, one per dictionary.
|
|
71
|
+
:rtype: list[dict[str, str]]
|
|
72
|
+
"""
|
|
73
|
+
with Path(csv_filename).open(newline='', encoding='utf-8') as input_file:
|
|
74
|
+
return list(csv.DictReader(input_file, delimiter=delimiter))
|