diff --git a/src/ppclock/cli.py b/src/ppclock/cli.py index fd8dd02..4aaa926 100644 --- a/src/ppclock/cli.py +++ b/src/ppclock/cli.py @@ -103,6 +103,7 @@ def build_parser() -> argparse.ArgumentParser: sp = sub.add_parser("time", help="对时(默认当前本地时间)") sp.add_argument("datetime", nargs="?", help="ISO8601,如 2026-07-24T15:30:00") + sp.add_argument("--tz", type=float, help="时区偏移(小时,如 8=北京;仅无显式时间时生效)") sp = sub.add_parser("mode", help="显示模式") sp.add_argument("name", choices=sorted(P.MODES)) @@ -191,6 +192,9 @@ async def _run_command(args, t): if c == "time": dt = (datetime.datetime.fromisoformat(args.datetime) if args.datetime else None) + if dt is None and args.tz is not None: + tz = datetime.timezone(datetime.timedelta(hours=args.tz)) + dt = datetime.datetime.now(tz).replace(tzinfo=None) await C.set_time(t, dt) return {"set": (dt or datetime.datetime.now()).isoformat()} if c == "mode": diff --git a/tests/test_cli.py b/tests/test_cli.py index 604a153..c4b9b1b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -286,3 +286,17 @@ class TestViaBridge: code, _ = run_cli(capsys, ["--json", "scan"]) assert code == 0 assert called["args"] == ("10.0.0.7", 8971) + + +class TestTimeTz: + def test_tz_offset_applied(self, capsys, monkeypatch): + """--tz 8 应写入北京墙钟(与系统 UTC 本地时相差 8h)""" + import datetime as _dt + code, out = run_cli(capsys, ["--json", "time", "--tz", "8"]) + assert code == 0 + sent = FakeTransport.instances[0].rxtx_writes[0] + # dd 帧的 unix 字段(本地墙钟按 UTC 计)反解小时 + unix_local = int.from_bytes(sent[1:5], "big") + wall = _dt.datetime.fromtimestamp(unix_local, _dt.timezone.utc) + utc_now = _dt.datetime.now(_dt.timezone.utc) + assert abs((wall - utc_now).total_seconds() - 8 * 3600) < 120