簡體   English   中英

將當前日期時間與包括分鍾在內的一天中的時間進行比較

[英]Compare current datetime to time of day that includes minutes

將當前日期時間與一天中包含分鍾的時間進行比較的最佳方法是什么。 我目前的方法似乎不是最簡潔的。 我想在下午 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 之前做,事情會變得更加混亂。

我會這樣做:

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)

您可以使用我為我的一個項目構建的這個 function。 我把這個 function 建立在日、時、分、秒級別。 我已經根據您的需要減少了它。

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)

您可以根據需要重復使用 function。 例如:

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

這與使用“between”選項基本相同。

您可以簡單地從datetime時間 object 中提取time object 並進行直接比較。

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM