跳转至

utilles

to_datetime(base) 🔗

将适宜的对象转化为 datetime 类型.

Parameters:

Name Type Description Default
base TimeObject

要转化的对象, 字符串应为 ISO 时间 / 日期格式, 浮点数为时间戳.

required

Raises:

Type Description
ValueError

字符串格式错误.

Returns:

Name Type Description
datetime datetime

转化成的 datetime.

Source code in src/graia/scheduler/utilles.py
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
def to_datetime(
    base: TimeObject,
) -> datetime:
    """将适宜的对象转化为 datetime 类型.

    Args:
        base (TimeObject): 要转化的对象, 字符串应为 ISO 时间 / 日期格式, 浮点数为时间戳.

    Raises:
        ValueError: 字符串格式错误.

    Returns:
        datetime: 转化成的 datetime.
    """
    start = datetime.now()
    if isinstance(base, datetime):
        return base
    elif isinstance(base, time):
        return datetime.fromisoformat(f"{start.date()} {base.isoformat()}")
    elif isinstance(base, float):
        return datetime.fromtimestamp(base)
    else:
        if "-" in base:  # Base is from datetime.isoformat()
            return datetime.fromisoformat(base)
        elif ":" in base:  # Base is from time.isoformat()
            return datetime.fromisoformat(f"{start.date()} {base}")
        else:
            raise ValueError("Expected an ISO style time string!")