56 lines
2.3 KiB
Python
Executable File
56 lines
2.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# datecalc - date arithmetic: add/subtract days, difference between dates, weekday
|
|
# Usage: datecalc [DATE] [--add N] [--sub N] [--diff DATE2] [--weekday] [--format FMT]
|
|
# DATE defaults to today. Dates are YYYY-MM-DD (also accepts YYYY/MM/DD).
|
|
import argparse, sys
|
|
from datetime import date, timedelta
|
|
|
|
def parse(s):
|
|
s = s.strip().replace("/", "-")
|
|
y, m, d = (int(x) for x in s.split("-"))
|
|
return date(y, m, d)
|
|
|
|
def selftest():
|
|
assert parse("2026-01-01") + timedelta(days=10) == date(2026, 1, 11)
|
|
assert parse("2026-01-11") - timedelta(days=10) == date(2026, 1, 1)
|
|
assert (date(2026, 1, 11) - date(2026, 1, 1)).days == 10
|
|
assert date(2026, 1, 1).strftime("%A") == "Thursday"
|
|
assert parse("2026/02/28") + timedelta(days=1) == date(2026, 3, 1)
|
|
print("datecalc selftest: ok (add/sub/diff/weekday)")
|
|
return 0
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="datecalc",
|
|
description="Date arithmetic: add/subtract days, difference between dates, weekday.")
|
|
p.add_argument("date", nargs="?", default=None, help="start date YYYY-MM-DD (default: today)")
|
|
p.add_argument("--add", type=int, default=0, help="days to add")
|
|
p.add_argument("--sub", type=int, default=0, help="days to subtract")
|
|
p.add_argument("--diff", metavar="DATE2", help="show days between DATE and DATE2")
|
|
p.add_argument("--weekday", action="store_true", help="show the weekday of the result")
|
|
p.add_argument("--format", default="%Y-%m-%d", help="output date format (default %%Y-%%m-%%d)")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
try:
|
|
d = parse(a.date) if a.date else date.today()
|
|
except Exception as e:
|
|
print(f"datecalc: bad date: {e}", file=sys.stderr); return 2
|
|
if a.diff:
|
|
try:
|
|
d2 = parse(a.diff)
|
|
except Exception as e:
|
|
print(f"datecalc: bad --diff date: {e}", file=sys.stderr); return 2
|
|
delta = (d2 - d).days
|
|
print(f"{d} -> {d2}: {delta} day{'s' if abs(delta) != 1 else ''}")
|
|
return 0
|
|
d = d + timedelta(days=a.add - a.sub)
|
|
out = d.strftime(a.format)
|
|
if a.weekday:
|
|
out += f" ({d.strftime('%A')})"
|
|
print(out)
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|