scripts/workday_calc.py
18.9 KB| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | """工作日日期推算工具(离线,仅用标准库)。 |
| 4 | |
| 5 | 子命令: |
| 6 | check 判断某天是不是工作日 |
| 7 | diff 统计两个日期之间(含起止)的工作日天数 |
| 8 | add 从某天起按工作日正推 / 倒推若干天 |
| 9 | month 打印某月日历,标出工作日与休息日 |
| 10 | |
| 11 | 默认休息日为周六、周日;节假日与调休上班日通过 --holidays 传入外部文件, |
| 12 | 脚本本身不内置任何节假日数据,不做网络请求,也不写任何文件。 |
| 13 | """ |
| 14 | |
| 15 | import sys |
| 16 | import os |
| 17 | import json |
| 18 | import argparse |
| 19 | from datetime import date, timedelta |
| 20 | |
| 21 | WEEKDAY_NAMES = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] |
| 22 | |
| 23 | EXIT_OK = 0 |
| 24 | EXIT_BAD_ARG = 2 |
| 25 | EXIT_BAD_CALENDAR = 3 |
| 26 | |
| 27 | |
| 28 | def force_utf8_stdout(): |
| 29 | """避免 Windows 控制台默认编码导致输出报错。""" |
| 30 | for stream in (sys.stdout, sys.stderr): |
| 31 | if hasattr(stream, "reconfigure"): |
| 32 | try: |
| 33 | stream.reconfigure(encoding="utf-8", errors="replace") |
| 34 | except Exception: |
| 35 | pass |
| 36 | |
| 37 | |
| 38 | class CalendarError(Exception): |
| 39 | """节假日配置有误。""" |
| 40 | |
| 41 | |
| 42 | def parse_date(text, flag_name=""): |
| 43 | """解析 YYYY-MM-DD 或 YYYY/MM/DD 或 YYYYMMDD;非法则抛 ValueError。""" |
| 44 | raw = (text or "").strip() |
| 45 | if not raw: |
| 46 | raise ValueError("日期为空%s" % (("(%s)" % flag_name) if flag_name else "")) |
| 47 | normalized = raw.replace("/", "-").replace(".", "-") |
| 48 | parts = normalized.split("-") |
| 49 | if len(parts) == 1 and len(normalized) == 8 and normalized.isdigit(): |
| 50 | parts = [normalized[0:4], normalized[4:6], normalized[6:8]] |
| 51 | if len(parts) != 3: |
| 52 | raise ValueError("日期格式应为 YYYY-MM-DD,收到:%s" % raw) |
| 53 | try: |
| 54 | year, month, day = (int(p) for p in parts) |
| 55 | except ValueError: |
| 56 | raise ValueError("日期格式应为 YYYY-MM-DD,收到:%s" % raw) |
| 57 | if not (1 <= month <= 12): |
| 58 | raise ValueError("月份超出范围:%s" % raw) |
| 59 | if not (1 <= day <= 31): |
| 60 | raise ValueError("日超出范围:%s" % raw) |
| 61 | try: |
| 62 | return date(year, month, day) |
| 63 | except ValueError: |
| 64 | raise ValueError("不是真实存在的日期:%s" % raw) |
| 65 | |
| 66 | |
| 67 | def parse_year_month(text): |
| 68 | """解析 YYYY-MM,用于 month 子命令。""" |
| 69 | raw = (text or "").strip().replace("/", "-").replace(".", "-") |
| 70 | parts = [p for p in raw.split("-") if p] |
| 71 | if len(parts) == 2: |
| 72 | try: |
| 73 | year, month = int(parts[0]), int(parts[1]) |
| 74 | except ValueError: |
| 75 | raise ValueError("月份格式应为 YYYY-MM,收到:%s" % text) |
| 76 | elif len(parts) == 1 and len(raw) == 6 and raw.isdigit(): |
| 77 | year, month = int(raw[0:4]), int(raw[4:6]) |
| 78 | else: |
| 79 | raise ValueError("月份格式应为 YYYY-MM,收到:%s" % text) |
| 80 | if not (1 <= month <= 12): |
| 81 | raise ValueError("月份超出范围:%s" % text) |
| 82 | if not (1 <= year <= 9999): |
| 83 | raise ValueError("年份超出范围:%s" % text) |
| 84 | return year, month |
| 85 | |
| 86 | |
| 87 | def parse_rest_days(text): |
| 88 | """解析休息日:逗号分隔的 1~7(1=周一 … 7=周日)。""" |
| 89 | raw = (text or "").strip() |
| 90 | if not raw: |
| 91 | raise ValueError("休息日设置不能为空") |
| 92 | tokens = [t.strip() for t in raw.replace(",", ",").split(",") if t.strip()] |
| 93 | days = set() |
| 94 | for token in tokens: |
| 95 | if not token.isdigit(): |
| 96 | raise ValueError("休息日只能是 1~7 的数字,收到:%s" % token) |
| 97 | value = int(token) |
| 98 | if not (1 <= value <= 7): |
| 99 | raise ValueError("休息日只能在 1~7 之间,收到:%s" % token) |
| 100 | days.add(value) |
| 101 | if len(days) >= 7: |
| 102 | raise ValueError("休息日不能把七天全占,最多 6 天") |
| 103 | return days |
| 104 | |
| 105 | |
| 106 | def load_calendar(path): |
| 107 | """读取节假日配置,返回 (holidays, workdays) 两个 {date: 名称} 字典。 |
| 108 | |
| 109 | 支持两种文件: |
| 110 | 1) JSON:{"holidays": {...} 或 [...], "workdays": {...} 或 [...]} |
| 111 | - 字典形式 {"2026-01-01": "元旦"} |
| 112 | - 列表形式 ["2026-01-01"],名称为空 |
| 113 | 2) 纯文本(其它扩展名):每行一条 |
| 114 | - 以 # 开头的注释行忽略 |
| 115 | - "2026-01-01 元旦" 表示节假日 |
| 116 | - "+2026-01-04 调休上班" 表示调休上班日 |
| 117 | """ |
| 118 | if not os.path.isfile(path): |
| 119 | raise CalendarError("找不到节假日文件:%s" % path) |
| 120 | try: |
| 121 | with open(path, "r", encoding="utf-8-sig") as handle: |
| 122 | text = handle.read() |
| 123 | except OSError as exc: |
| 124 | raise CalendarError("读取节假日文件失败:%s" % exc) |
| 125 | except UnicodeDecodeError: |
| 126 | raise CalendarError("节假日文件不是 UTF-8 编码,请另存为 UTF-8") |
| 127 | |
| 128 | holidays = {} |
| 129 | workdays = {} |
| 130 | |
| 131 | def add_entry(target, key, name, source): |
| 132 | try: |
| 133 | parsed = parse_date(key) |
| 134 | except ValueError as exc: |
| 135 | raise CalendarError("%s里的日期无效:%s" % (source, exc)) |
| 136 | if parsed in target and target[parsed] != name: |
| 137 | raise CalendarError( |
| 138 | "%s里的日期 %s 重复且名称不同(%s / %s)" |
| 139 | % (source, parsed.isoformat(), target[parsed], name) |
| 140 | ) |
| 141 | target[parsed] = name |
| 142 | |
| 143 | def walk(node, target, source): |
| 144 | if isinstance(node, dict): |
| 145 | for key, name in node.items(): |
| 146 | add_entry(target, str(key), str(name or "").strip(), source) |
| 147 | elif isinstance(node, list): |
| 148 | for key in node: |
| 149 | add_entry(target, str(key), "", source) |
| 150 | elif node is None: |
| 151 | return |
| 152 | else: |
| 153 | raise CalendarError("%s的格式不对,应为对象或数组" % source) |
| 154 | |
| 155 | stripped = text.strip() |
| 156 | looks_like_json = stripped.startswith("{") or stripped.startswith("[") |
| 157 | if path.lower().endswith(".json") or looks_like_json: |
| 158 | try: |
| 159 | data = json.loads(stripped) if stripped else {} |
| 160 | except json.JSONDecodeError as exc: |
| 161 | raise CalendarError("节假日 JSON 解析失败:%s" % exc) |
| 162 | if not isinstance(data, dict): |
| 163 | raise CalendarError("节假日 JSON 顶层应为对象,含 holidays 与 workdays 两个键") |
| 164 | unknown = [k for k in data.keys() if k not in ("holidays", "workdays")] |
| 165 | if unknown: |
| 166 | raise CalendarError( |
| 167 | "节假日 JSON 里有无法识别的键:%s(只支持 holidays 与 workdays)" |
| 168 | % "、".join(sorted(unknown)) |
| 169 | ) |
| 170 | walk(data.get("holidays"), holidays, "holidays") |
| 171 | walk(data.get("workdays"), workdays, "workdays") |
| 172 | else: |
| 173 | for lineno, line in enumerate(text.splitlines(), 1): |
| 174 | content = line.strip() |
| 175 | if not content or content.startswith("#"): |
| 176 | continue |
| 177 | target = holidays |
| 178 | if content.startswith("+"): |
| 179 | target = workdays |
| 180 | content = content[1:].strip() |
| 181 | pieces = content.split(None, 1) |
| 182 | key = pieces[0] |
| 183 | name = pieces[1].strip() if len(pieces) > 1 else "" |
| 184 | add_entry(target, key, name, "节假日文件第 %d 行" % lineno) |
| 185 | |
| 186 | both = set(holidays) & set(workdays) |
| 187 | if both: |
| 188 | first = sorted(both)[0].isoformat() |
| 189 | raise CalendarError( |
| 190 | "日期 %s 同时被列为节假日和调休上班日,请删掉其中一条(共 %d 个冲突)" |
| 191 | % (first, len(both)) |
| 192 | ) |
| 193 | return holidays, workdays |
| 194 | |
| 195 | |
| 196 | class WorkCalendar(object): |
| 197 | def __init__(self, rest_days=None, holidays=None, workdays=None, today=None): |
| 198 | self.rest_days = set(rest_days or {6, 7}) |
| 199 | self.holidays = dict(holidays or {}) |
| 200 | self.workdays = dict(workdays or {}) |
| 201 | |
| 202 | def classify(self, day): |
| 203 | """返回 (是否工作日, 说明)。""" |
| 204 | label = WEEKDAY_NAMES[day.isoweekday() - 1] |
| 205 | if day in self.holidays: |
| 206 | name = self.holidays[day] |
| 207 | return False, ("节假日" + (":" + name if name else "")) |
| 208 | if day in self.workdays: |
| 209 | name = self.workdays[day] |
| 210 | return True, ("调休上班" + (":" + name if name else "")) |
| 211 | if day.isoweekday() in self.rest_days: |
| 212 | return False, "周末休息(%s)" % label |
| 213 | return True, "正常工作日(%s)" % label |
| 214 | |
| 215 | def is_workday(self, day): |
| 216 | return self.classify(day)[0] |
| 217 | |
| 218 | def count(self, start, end): |
| 219 | """统计 [start, end] 闭区间内的工作日,返回明细字典。""" |
| 220 | total_present = 0 |
| 221 | workday_count = 0 |
| 222 | holiday_count = 0 |
| 223 | extra_count = 0 |
| 224 | weekend_count = 0 |
| 225 | current = start |
| 226 | one_day = timedelta(days=1) |
| 227 | while current <= end: |
| 228 | total_present += 1 |
| 229 | is_work, reason = self.classify(current) |
| 230 | if is_work: |
| 231 | workday_count += 1 |
| 232 | if current in self.workdays: |
| 233 | extra_count += 1 |
| 234 | else: |
| 235 | if current in self.holidays: |
| 236 | holiday_count += 1 |
| 237 | else: |
| 238 | weekend_count += 1 |
| 239 | current += one_day |
| 240 | return { |
| 241 | "total_days": total_present, |
| 242 | "workdays": workday_count, |
| 243 | "rest_days": total_present - workday_count, |
| 244 | "weekend_rest": weekend_count, |
| 245 | "holiday_rest": holiday_count, |
| 246 | "extra_workdays": extra_count, |
| 247 | } |
| 248 | |
| 249 | def add_workdays(self, start, offset): |
| 250 | """从 start 起(不含 start)推 |offset| 个工作日;0 表示 start 当天或其后的首个工作日。""" |
| 251 | if offset == 0: |
| 252 | current = start |
| 253 | guard = 0 |
| 254 | while not self.is_workday(current): |
| 255 | current += timedelta(days=1) |
| 256 | guard += 1 |
| 257 | if guard > 3660: |
| 258 | raise CalendarError("连续十年都没有工作日,请检查休息日与节假日配置") |
| 259 | return current |
| 260 | step = timedelta(days=1 if offset > 0 else -1) |
| 261 | remaining = abs(offset) |
| 262 | current = start |
| 263 | guard = 0 |
| 264 | while remaining > 0: |
| 265 | current += step |
| 266 | if self.is_workday(current): |
| 267 | remaining -= 1 |
| 268 | guard += 1 |
| 269 | if guard > 366 * 200: |
| 270 | raise CalendarError("推算超过 200 年,请检查休息日与节假日配置") |
| 271 | return current |
| 272 | |
| 273 | |
| 274 | def output(payload, as_json): |
| 275 | try: |
| 276 | if as_json: |
| 277 | print(json.dumps(payload, ensure_ascii=False, indent=2)) |
| 278 | return |
| 279 | for line in payload["text"]: |
| 280 | print(line) |
| 281 | except BrokenPipeError: |
| 282 | # 输出被管道下游提前关闭(例如 | head),安静退出而不是抛栈 |
| 283 | try: |
| 284 | sys.stdout.close() |
| 285 | except Exception: |
| 286 | pass |
| 287 | os._exit(EXIT_OK) |
| 288 | |
| 289 | |
| 290 | def add_common_args(target, sub_level=False): |
| 291 | """公共选项;放在子命令后面也认,默认值只由顶层解析器负责。""" |
| 292 | kwargs = {"default": argparse.SUPPRESS} if sub_level else {} |
| 293 | target.add_argument( |
| 294 | "--holidays", |
| 295 | metavar="FILE", |
| 296 | help="节假日/调休配置文件(JSON 或纯文本),不传则只按周一至周五判断", |
| 297 | **kwargs |
| 298 | ) |
| 299 | repeat = {"default": argparse.SUPPRESS} if sub_level else {"default": "6,7"} |
| 300 | target.add_argument( |
| 301 | "--rest", |
| 302 | metavar="1-7", |
| 303 | help="每周休息日,逗号分隔,1=周一 … 7=周日,默认 6,7(周六周日);单休可传 7", |
| 304 | **repeat |
| 305 | ) |
| 306 | target.add_argument( |
| 307 | "--json", action="store_true", help="以 JSON 输出,便于程序处理", **kwargs |
| 308 | ) |
| 309 | |
| 310 | |
| 311 | def build_parser(): |
| 312 | parser = argparse.ArgumentParser( |
| 313 | prog="workday_calc.py", |
| 314 | description="工作日日期推算工具:判断工作日、统计工作日天数、按工作日正推倒推、打印月度工作日日历。", |
| 315 | ) |
| 316 | add_common_args(parser) |
| 317 | |
| 318 | sub = parser.add_subparsers(dest="command", metavar="子命令") |
| 319 | |
| 320 | check = sub.add_parser("check", help="判断某天是不是工作日") |
| 321 | add_common_args(check, sub_level=True) |
| 322 | check.add_argument("day", help="要判断的日期,如 2026-11-23") |
| 323 | |
| 324 | diff = sub.add_parser("diff", help="统计两个日期之间的工作日天数") |
| 325 | add_common_args(diff, sub_level=True) |
| 326 | diff.add_argument("start", help="起始日期,如 2026-11-01") |
| 327 | diff.add_argument("end", help="结束日期,如 2026-11-30") |
| 328 | |
| 329 | add = sub.add_parser("add", help="从某天起按工作日正推或倒推") |
| 330 | add_common_args(add, sub_level=True) |
| 331 | add.add_argument("day", help="起算日期,如 2026-11-20") |
| 332 | add.add_argument("offset", type=int, help="工作日个数,正数为向后推,负数为向前推") |
| 333 | |
| 334 | month = sub.add_parser("month", help="打印某月日历并标出工作日与休息日") |
| 335 | add_common_args(month, sub_level=True) |
| 336 | month.add_argument("year_month", help="年月,如 2026-11") |
| 337 | |
| 338 | template = sub.add_parser("template", help="打印一份节假日配置文件的模板(内容整行复制即可用)") |
| 339 | add_common_args(template, sub_level=True) |
| 340 | |
| 341 | return parser |
| 342 | |
| 343 | |
| 344 | def main(argv=None): |
| 345 | force_utf8_stdout() |
| 346 | parser = build_parser() |
| 347 | args = parser.parse_args(argv) |
| 348 | |
| 349 | if not args.command: |
| 350 | parser.print_help() |
| 351 | return EXIT_BAD_ARG |
| 352 | |
| 353 | try: |
| 354 | rest_days = parse_rest_days(args.rest) |
| 355 | except ValueError as exc: |
| 356 | print("参数错误:%s" % exc, file=sys.stderr) |
| 357 | return EXIT_BAD_ARG |
| 358 | |
| 359 | holidays, workdays = {}, {} |
| 360 | if args.holidays: |
| 361 | try: |
| 362 | holidays, workdays = load_calendar(args.holidays) |
| 363 | except CalendarError as exc: |
| 364 | print("节假日配置错误:%s" % exc, file=sys.stderr) |
| 365 | return EXIT_BAD_CALENDAR |
| 366 | |
| 367 | cal = WorkCalendar(rest_days=rest_days, holidays=holidays, workdays=workdays) |
| 368 | |
| 369 | try: |
| 370 | if args.command == "template": |
| 371 | skeleton = { |
| 372 | "holidays": {"YYYY-MM-DD": "节假日名称(可留空)"}, |
| 373 | "workdays": {"YYYY-MM-DD": "调休上班名称(可留空)"}, |
| 374 | } |
| 375 | text = [ |
| 376 | "把下面内容另存为 holidays.json,按实际安排替换日期,再用 --holidays holidays.json 传入:", |
| 377 | json.dumps(skeleton, ensure_ascii=False, indent=2), |
| 378 | ] |
| 379 | output({"holidays": skeleton["holidays"], "workdays": skeleton["workdays"], "text": text}, args.json) |
| 380 | |
| 381 | elif args.command == "check": |
| 382 | day = parse_date(args.day, "日期") |
| 383 | is_work, reason = cal.classify(day) |
| 384 | text = [ |
| 385 | "日期:%s(%s)" % (day.isoformat(), WEEKDAY_NAMES[day.isoweekday() - 1]), |
| 386 | "结论:%s" % ("工作日" if is_work else "非工作日"), |
| 387 | "依据:%s" % reason, |
| 388 | ] |
| 389 | output( |
| 390 | { |
| 391 | "date": day.isoformat(), |
| 392 | "weekday": WEEKDAY_NAMES[day.isoweekday() - 1], |
| 393 | "is_workday": is_work, |
| 394 | "reason": reason, |
| 395 | "text": text, |
| 396 | }, |
| 397 | args.json, |
| 398 | ) |
| 399 | |
| 400 | elif args.command == "diff": |
| 401 | start = parse_date(args.start, "起始日期") |
| 402 | end = parse_date(args.end, "结束日期") |
| 403 | if start > end: |
| 404 | start, end = end, start |
| 405 | detail = cal.count(start, end) |
| 406 | text = [ |
| 407 | "区间:%s 至 %s(含两端)" % (start.isoformat(), end.isoformat()), |
| 408 | "自然日:%d 天" % detail["total_days"], |
| 409 | "工作日:%d 天" % detail["workdays"], |
| 410 | "休息日:%d 天(其中周末 %d 天、节假日 %d 天)" |
| 411 | % (detail["rest_days"], detail["weekend_rest"], detail["holiday_rest"]), |
| 412 | ] |
| 413 | if detail["extra_workdays"]: |
| 414 | text.append("其中调休上班:%d 天" % detail["extra_workdays"]) |
| 415 | payload = {"start": start.isoformat(), "end": end.isoformat(), "inclusive": True} |
| 416 | payload.update(detail) |
| 417 | payload["text"] = text |
| 418 | output(payload, args.json) |
| 419 | |
| 420 | elif args.command == "add": |
| 421 | day = parse_date(args.day, "起算日期") |
| 422 | result = cal.add_workdays(day, args.offset) |
| 423 | is_work, reason = cal.classify(result) |
| 424 | direction = "向后" if args.offset > 0 else ("向前" if args.offset < 0 else "当天或之后") |
| 425 | text = [ |
| 426 | "起算日期:%s(%s,%s)" |
| 427 | % (day.isoformat(), WEEKDAY_NAMES[day.isoweekday() - 1], "工作日" if cal.is_workday(day) else "非工作日"), |
| 428 | "%s %d 个工作日 => %s(%s)" |
| 429 | % ( |
| 430 | direction, |
| 431 | abs(args.offset), |
| 432 | result.isoformat(), |
| 433 | WEEKDAY_NAMES[result.isoweekday() - 1], |
| 434 | ), |
| 435 | "结果状态:%s(%s)" % ("工作日" if is_work else "非工作日", reason), |
| 436 | ] |
| 437 | output( |
| 438 | { |
| 439 | "start": day.isoformat(), |
| 440 | "offset": args.offset, |
| 441 | "date": result.isoformat(), |
| 442 | "weekday": WEEKDAY_NAMES[result.isoweekday() - 1], |
| 443 | "is_workday": is_work, |
| 444 | "reason": reason, |
| 445 | "text": text, |
| 446 | }, |
| 447 | args.json, |
| 448 | ) |
| 449 | |
| 450 | elif args.command == "month": |
| 451 | year, mon = parse_year_month(args.year_month) |
| 452 | first = date(year, mon, 1) |
| 453 | if mon == 12: |
| 454 | next_first = date(year + 1, 1, 1) |
| 455 | else: |
| 456 | next_first = date(year, mon + 1, 1) |
| 457 | last = next_first - timedelta(days=1) |
| 458 | detail = cal.count(first, last) |
| 459 | text = ["%d 年 %02d 月:工作日 %d 天,休息 %d 天" |
| 460 | % (year, mon, detail["workdays"], detail["rest_days"])] |
| 461 | text.append("日期 星期 状态") |
| 462 | rows = [] |
| 463 | current = first |
| 464 | while current <= last: |
| 465 | is_work, reason = cal.classify(current) |
| 466 | rows.append( |
| 467 | { |
| 468 | "date": current.isoformat(), |
| 469 | "weekday": WEEKDAY_NAMES[current.isoweekday() - 1], |
| 470 | "is_workday": is_work, |
| 471 | "reason": reason, |
| 472 | } |
| 473 | ) |
| 474 | text.append( |
| 475 | "%s %s %s" |
| 476 | % (current.isoformat(), WEEKDAY_NAMES[current.isoweekday() - 1], "上班" if is_work else "休息") |
| 477 | ) |
| 478 | current += timedelta(days=1) |
| 479 | payload = { |
| 480 | "year": year, |
| 481 | "month": mon, |
| 482 | "days": rows, |
| 483 | "text": text, |
| 484 | } |
| 485 | payload.update(detail) |
| 486 | output(payload, args.json) |
| 487 | |
| 488 | else: |
| 489 | parser.print_help() |
| 490 | return EXIT_BAD_ARG |
| 491 | except ValueError as exc: |
| 492 | print("日期错误:%s" % exc, file=sys.stderr) |
| 493 | return EXIT_BAD_ARG |
| 494 | except CalendarError as exc: |
| 495 | print("推算失败:%s" % exc, file=sys.stderr) |
| 496 | return EXIT_BAD_CALENDAR |
| 497 | return EXIT_OK |
| 498 | |
| 499 | |
| 500 | if __name__ == "__main__": |
| 501 | sys.exit(main()) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

