forked from NekoiMeiov/astrbot_plugin_reneban
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtime_utils.py
More file actions
55 lines (48 loc) · 1.6 KB
/
Copy pathtime_utils.py
File metadata and controls
55 lines (48 loc) · 1.6 KB
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
# 所有时间转换都在这里
import re
_TIME_RE = re.compile(
r"^(?=.*\d)(?:(?P<days>\d+)d)?(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?(?:(?P<seconds>\d+)s?)?$"
)
def time_remaining_format(time_last: float) -> str:
"""
将剩余秒数格式化为易读的时间描述
"""
if time_last < 0:
return "已过期"
if time_last == float("inf"):
return "永久"
time_last = int(time_last)
# 按照从大到小的单位进行转换
days = time_last // 86400
hours = (time_last % 86400) // 3600
minutes = (time_last % 3600) // 60
seconds = time_last % 60
# 构建易读的时间描述
result = []
if days > 0:
result.append(f"{days}天")
if hours > 0:
result.append(f"{hours}小时")
if minutes > 0:
result.append(f"{minutes}分钟")
if seconds > 0 or not result:
result.append(f"{seconds}秒")
return "".join(result)
def time_str_to_float(time_str: str) -> float:
"""
将时间字符串(如 1d2h3m4)转换为秒数
"""
if not time_str or time_str.lower() == "inf" or time_str == "0":
return float("inf")
# ^(?=.*\d)(?:(?<days>\d+)d)?(?:(?<hours>\d+)h)?(?:(?<minutes>\d+)m)?(?:(?<seconds>\d+)s?)$
m = _TIME_RE.fullmatch(time_str)
if not m:
raise ValueError(f"非法的时间字符串格式: {time_str!r}")
# 命名捕获组一次性全取到,None 的转成 0
parts = {k: int(v or 0) for k, v in m.groupdict().items()}
return (
parts["days"] * 86400
+ parts["hours"] * 3600
+ parts["minutes"] * 60
+ parts["seconds"]
)