File size: 2,397 Bytes
0163d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ec4669
 
 
 
 
 
 
 
 
 
 
0163d21
 
 
 
 
 
8ec4669
 
 
 
 
 
 
0163d21
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""时间工具,全部按 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")