并检查当前日期时间是否在特定范围内

2024-07-04 08:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试做类似于this的操作,但是我想用实际的工作日名称和时间指定开始日期和结束日期。例如,我想检查当前日期时间(日期时间。日期时间。现在())在星期二下午4:30到星期四上午11:45之间。这将每周更新,所以必须在周二/周四之前更新。在

我考虑过如何安排工作日(但我不知道如何将时间部分包装在其中):

TimeNow = datetime.datetime.now()

if TimeNow.weekday() >= 1 and TimeNow.weekday() <= 3:
    #runcodehere

有没有想过我该怎么做?在


Tags: and名称datetimeif时间thisnow工作日
3条回答

最简单的方法是使用一周内经过的分钟数:

def mins_in_week(day, hour, minute):
    return day * 24 * 60 + hour * 60 + minute

if (mins_in_week(1, 16, 30) < 
    mins_in_week(TimeNow.weekday(), TimeNow.hour, TimeNow.minute) < 
    mins_in_week(3, 11, 45)):
    ....

它不是很整洁,但这样的东西应该行得通:

TimeNow = datetime.datetime.now()

if (TimeNow.weekday() == 1 and ((TimeNow.hour() == 4 and TimeNow.minute >= 30) or TimeNow.hour > 4)) or (TimeNow.weekday() == 2) or (TimeNow.weekday() == 3 and (TimeNow.hour() < 11 or (TimeNow.hour() == 11 and TimeNow.minute <= 45)):
     #runcodehere

您可以使用andor的组合,并且每天都有不同的条件:

import datetime

TimeNow = datetime.datetime.now()

day_now = TimeNow.weekday()
time_now = TimeNow.hour*60 + TimeNow.minute

if (day_now == 1 and time_now > 990) or (day_now == 2) or (day_now == 3 and time_now < 705):
    # do something

相关问题 更多 >

    热门问题