Download utils/timeutil.py from kikl/kookbot: direct link, hf CLI and curl.
- Browser
- Download file 2.4 kB
-
https://huggingface.co/spaces/kikl/kookbot/resolve/main/utils/timeutil.py
- Command line
-
hf download hf://spaces/kikl/kookbot/utils/timeutil.py
-
curl -L -o timeutil.py https://huggingface.co/spaces/kikl/kookbot/resolve/main/utils/timeutil.py
2.4 kB
| """时间工具,全部按 UTC+8 计算。 | |
| 容器跑在海外(HF Spaces),系统时间是 UTC。任何地方只要用了 | |
| datetime.now() 而没带时区,打卡日期就会错 8 小时 —— 早上 8 点前的打卡 | |
| 会被算到前一天。所以这里统一收口,业务代码只从这里取时间。 | |
| """ | |
| from datetime import datetime, date, timedelta | |
| from core.config import CST, WEEK_START | |
| def now() -> datetime: | |
| """当前时间(带 +08:00 时区)""" | |
| return datetime.now(CST) | |
| def today() -> date: | |
| return now().date() | |
| def today_str() -> str: | |
| return today().isoformat() | |
| def week_start(day: date = None) -> date: | |
| """本周起始日。由 config.WEEK_START 决定周一还是周日。""" | |
| day = day or today() | |
| weekday = day.weekday() # 周一=0 ... 周日=6 | |
| if WEEK_START == "sunday": | |
| offset = (weekday + 1) % 7 # 周日=0 | |
| else: | |
| offset = weekday | |
| return day - timedelta(days=offset) | |
| def midnight(day: date) -> datetime: | |
| """某天的 00:00 (+08:00),用于 Mongo 范围查询""" | |
| return datetime(day.year, day.month, day.day, tzinfo=CST) | |
| def minutes_between(start: datetime, end: datetime) -> int: | |
| return int((end - start).total_seconds() // 60) | |
| def fmt_minutes(minutes) -> str: | |
| """125 -> '2小时5分'""" | |
| if minutes is None: | |
| return "—" | |
| minutes = int(minutes) | |
| sign = "-" if minutes < 0 else "" | |
| minutes = abs(minutes) | |
| h, m = divmod(minutes, 60) | |
| if h and m: | |
| return f"{sign}{h}小时{m}分" | |
| if h: | |
| return f"{sign}{h}小时" | |
| return f"{sign}{m}分" | |
| def fmt_hours(minutes) -> str: | |
| """125 -> '2.08'(小时,保留两位小数)。 | |
| 客户给的参照格式是「4.01 小时」这种十进制小时,打卡结果消息按这个来。 | |
| 列表里仍用 fmt_minutes 的「X小时Y分」,那种更适合扫读。 | |
| """ | |
| if minutes is None: | |
| return "—" | |
| return f"{int(minutes) / 60:.2f}" | |
| def fmt_datetime(dt: datetime) -> str: | |
| if not dt: | |
| return "—" | |
| return dt.astimezone(CST).strftime("%m-%d %H:%M") | |
| def fmt_datetime_sec(dt: datetime) -> str: | |
| """'2026-09-22 12:28:35' —— 打卡结果消息用,参照格式里带秒和年。""" | |
| if not dt: | |
| return "—" | |
| return dt.astimezone(CST).strftime("%Y-%m-%d %H:%M:%S") | |
| def fmt_date(d: date) -> str: | |
| return d.strftime("%m-%d") | |