将当前日期时间与一天中包含分钟的时间进行比较

发布于 2025-01-12 12:37:05 字数 287 浏览 1 评论 0原文

将当前日期时间与一天中包含分钟的时间进行比较的最佳方法是什么。我目前的方法似乎不是最简洁的。我想在下午 6:30 之后执行一条语句。

from datetime import datetime as dt

if (dt.now().hour == 18 and dt.now().minute > 30) or dt.now().hour >= 19:
    print('hello world')

如果我想在下午 6:30 之后和晚上 9:30 之前进行,事情会变得更加混乱。

What's the best way to compare the current datetime to a time of day that includes minutes. My current method doesn't seem the most concise. I want to execute a statement after 6:30PM.

from datetime import datetime as dt

if (dt.now().hour == 18 and dt.now().minute > 30) or dt.now().hour >= 19:
    print('hello world')

It gets even messier if I want to do after 6:30PM and before 9:30PM.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吻泪 2025-01-19 12:37:05

您只需从 datetime 对象中提取 time 对象并进行直接比较即可。

>>> from datetime import time, datetime as dt
>>> dt.now()
datetime.datetime(2022, 3, 8, 15, 0, 56, 393436)
>>> dt.now().time() > time(14, 30)
True
>>> dt.now().time() > time(15, 30)
False

You can simply extract a time object from your datetime object and make a direct comparison.

>>> from datetime import time, datetime as dt
>>> dt.now()
datetime.datetime(2022, 3, 8, 15, 0, 56, 393436)
>>> dt.now().time() > time(14, 30)
True
>>> dt.now().time() > time(15, 30)
False
月竹挽风 2025-01-19 12:37:05

我会这样做:

from datetime import datetime

def check_time(date, hour, minute):
    if date > date.replace(hour=hour, minute=minute):
        print('its more than ' + str(hour) + ':' + str(minute))
    else:
        print('its less than ' + str(hour) + ':' + str(minute))

today = datetime.now()
check_time(today, 18, 30)

I would do this:

from datetime import datetime

def check_time(date, hour, minute):
    if date > date.replace(hour=hour, minute=minute):
        print('its more than ' + str(hour) + ':' + str(minute))
    else:
        print('its less than ' + str(hour) + ':' + str(minute))

today = datetime.now()
check_time(today, 18, 30)
半城柳色半声笛 2025-01-19 12:37:05

您可以使用我为我的一个项目构建的这个函数。我在日、小时、分钟、秒级别上构建了这个功能。我已经根据您的需要减少了它。

def compare_hours(constraint: dict) -> bool:
    from datetime import datetime
    """
    This is used to compare a given hours,minutes against current time
    The constraint must contain a single key and value.
    Accepted keys are: 
        1. before:
            eg {"before": "17:30"}
        2. after:
            eg: {"after": "17:30"}
        3. between:
            eg: {"between": "17:30, 18:30"}
        4. equal:
            eg: {"equal": "15:30"}

    Parameters
    ----------
    constraint : dict
        A dictionary with keys like before, after, between and equal with their corresponding values.

    Returns
    -------
    True if constraint matches else False

    """
    accepted_keys = ("before", "after", "between", "equal")
    assert isinstance(constraint, dict), "Constraint must be a dict object"
    assert len(constraint.keys()) == 1, "Constraint contains 0 or more than 1 keys, only 1 is allowed"
    assert list(constraint.keys())[0] in accepted_keys, f"Invalid key provided. Accepted keys are {accepted_keys}"
    key = list(constraint.keys())[0]
    time_split = lambda x: list(map(int, x.split(":")))
    try:
        if key == "before":
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt < dt.replace(hour=hours, minute=minutes):
                return True
            return False
        elif key == "after":
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt > dt.replace(hour=hours, minute=minutes):
                return True
            return False
        elif key == "between":
            dt = datetime.now()
            values = constraint.get(key).replace(' ', '').split(",")
            assert len(values) == 2, "Invalid set of constraints given for between comparison"
            hours, minutes = time_split(values[0])
            dt1 = dt.replace(hour=hours, minute=minutes)
            hours, minutes = time_split(values[1])
            dt2 = dt.replace(hour=hours, minute=minutes)
            assert dt2 > dt1, "The 1st item in between must be smaller than second item"
            if dt > dt1 and dt < dt2:
                return True
            return False
        else:
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt == dt.replace(hour=hours, minute=minutes):
                return True
            return False
    except Exception as e:
        print(e)

您可以根据需要重复使用该功能。例如:

if compare_hours({"before": "21:00"}) and compre_hours({"after": "18:30"}):
    "do something"

这本质上与使用“ Between”选项相同。

You can use this function which I built for one of my projects. I had this function built at day, hour, minute, second level. I have reduced it for your needs.

def compare_hours(constraint: dict) -> bool:
    from datetime import datetime
    """
    This is used to compare a given hours,minutes against current time
    The constraint must contain a single key and value.
    Accepted keys are: 
        1. before:
            eg {"before": "17:30"}
        2. after:
            eg: {"after": "17:30"}
        3. between:
            eg: {"between": "17:30, 18:30"}
        4. equal:
            eg: {"equal": "15:30"}

    Parameters
    ----------
    constraint : dict
        A dictionary with keys like before, after, between and equal with their corresponding values.

    Returns
    -------
    True if constraint matches else False

    """
    accepted_keys = ("before", "after", "between", "equal")
    assert isinstance(constraint, dict), "Constraint must be a dict object"
    assert len(constraint.keys()) == 1, "Constraint contains 0 or more than 1 keys, only 1 is allowed"
    assert list(constraint.keys())[0] in accepted_keys, f"Invalid key provided. Accepted keys are {accepted_keys}"
    key = list(constraint.keys())[0]
    time_split = lambda x: list(map(int, x.split(":")))
    try:
        if key == "before":
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt < dt.replace(hour=hours, minute=minutes):
                return True
            return False
        elif key == "after":
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt > dt.replace(hour=hours, minute=minutes):
                return True
            return False
        elif key == "between":
            dt = datetime.now()
            values = constraint.get(key).replace(' ', '').split(",")
            assert len(values) == 2, "Invalid set of constraints given for between comparison"
            hours, minutes = time_split(values[0])
            dt1 = dt.replace(hour=hours, minute=minutes)
            hours, minutes = time_split(values[1])
            dt2 = dt.replace(hour=hours, minute=minutes)
            assert dt2 > dt1, "The 1st item in between must be smaller than second item"
            if dt > dt1 and dt < dt2:
                return True
            return False
        else:
            hours, minutes = time_split(constraint.get(key))
            dt = datetime.now()
            if dt == dt.replace(hour=hours, minute=minutes):
                return True
            return False
    except Exception as e:
        print(e)

You can reuse the function for your need. For eg:

if compare_hours({"before": "21:00"}) and compre_hours({"after": "18:30"}):
    "do something"

This is essentially the same as using the "between" option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文