我正在尝试执行与this类似的操作,但我想按实际工作日的名称和时间指定开始日期和结束日期。例如,我想检查当前的datetime(datetime.datetime.now())是否在星期二下午4:30到星期四上午11:45之间。这将每周更新,因此它必须是周二/周四的心态。
我已经考虑过如何平日工作(但我不知道如何将时间部分包含在其中):
TimeNow = datetime.datetime.now()
if TimeNow.weekday() >= 1 and TimeNow.weekday() <= 3:
#runcodehere
关于我将如何做到这一点的任何想法?
答案 0 :(得分:4)
最好的方法是使用一周内经过的分钟数:
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)):
....
答案 1 :(得分:2)
这不是很整洁,但这样的事情应该有效:
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
答案 2 :(得分:0)
您可以使用and
和or
的组合,并且每天都有不同的条件:
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