Initial commit

This commit is contained in:
Кокос Артем Николаевич
2026-01-21 15:58:31 +07:00
commit 004acf99d9
4 changed files with 153 additions and 0 deletions

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Artem Kokos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

28
README.md Normal file
View File

@@ -0,0 +1,28 @@
# datediff
Простая утилита командной строки для вычисления разницы между двумя датами в днях и полных годах.
## Установка
Скрипт не требует установки — достаточно иметь Python 3.7+.
## Использование
```sh
# Разница между указанной датой и сегодня
./datediff.py 2020-01-01
# Разница между двумя датами
./datediff.py 2020-01-01 2025-12-31
```
Формат даты: `YYYY-MM-DD`.
Вывод:
```
Дней: 2191, Полных лет: 5
```
## Лицензия
MIT — см. файл [LICENSE](LICENSE).

82
datediff.py Executable file
View File

@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""
Утилита для вычисления разницы между двумя датами.
Поддерживает:
- Разницу в днях и полных годах.
- Автоматическое сравнение с текущей датой при указании одной даты.
Формат даты: YYYY-MM-DD
"""
import sys
from datetime import date, datetime
def parse_date(date_str: str) -> date:
"""Преобразует строку вида 'YYYY-MM-DD' в объект date."""
if not isinstance(date_str, str):
raise TypeError("Ожидалась строка с датой")
return datetime.strptime(date_str.strip(), "%Y-%m-%d").date()
def years_between(start: date, end: date) -> int:
"""
Возвращает количество полных лет между двумя датами.
Учитывает високосные годы (например, 29 февраля).
"""
if start > end:
start, end = end, start
try:
candidate = start.replace(year=end.year)
except ValueError:
# Обработка 29 февраля в невисокосный год
candidate = start.replace(year=end.year, day=28)
years = end.year - start.year
if candidate > end:
years -= 1
return years
def days_between(start: date, end: date) -> int:
"""Возвращает абсолютное количество дней между двумя датами."""
return abs((end - start).days)
def diff_dates(d1: date, d2: date) -> tuple[int, int]:
"""
Возвращает кортеж (дней, полных лет) между двумя датами.
Порядок дат не важен — результат всегда положительный.
"""
days = days_between(d1, d2)
years = years_between(d1, d2)
return days, years
def main() -> None:
args = sys.argv[1:]
if not args or len(args) > 2:
print("Использование:", file=sys.stderr)
print(" datediff <дата> # от даты до сегодня", file=sys.stderr)
print(" datediff <дата1> <дата2> # между двумя датами", file=sys.stderr)
print("Формат даты: YYYY-MM-DD", file=sys.stderr)
sys.exit(1)
try:
d1 = parse_date(args[0])
d2 = parse_date(args[1]) if len(args) == 2 else date.today()
except (ValueError, TypeError) as e:
print(f"Ошибка: неверный формат даты — {e}", file=sys.stderr)
sys.exit(1)
days, years = diff_dates(d1, d2)
print(f"Дней: {days}, Полных лет: {years}")
if __name__ == "__main__":
main()

22
pyproject.toml Normal file
View File

@@ -0,0 +1,22 @@
[build-system]
requires = ["setuptools >= 61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "datediff"
version = "1.0.0"
description = "CLI utility to compute difference between two dates in days and full years"
readme = "README.md"
license = { text = "MIT" }
authors = [{ name = "Artem Kokos", email = "artem-kokos@mail.com" }]
requires-python = ">=3.7"
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Intended Audience :: Developers",
"Topic :: Utilities",
]
[project.scripts]
datediff = "datediff:main"