在python中如何检查它是否在工作日(周一至周五)以及时间是在上午10点到下午3点之间?
答案 0 :(得分:27)
>>> import datetime
>>> d = datetime.datetime.now()
# => datetime.datetime(2009, 12, 15, 13, 50, 35, 833175)
# check if weekday is 1..5
>>> d.isoweekday() in range(1, 6)
True
# check if hour is 10..15
>>> d.hour in range(10, 15)
True
# check if minute is 30
>>> d.minute==30
False
答案 1 :(得分:1)
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 12, 15, 12, 45, 33, 781000)
>>> now.isoweekday()
2 # Tuesday
上午10点至下午3点之间的时间就在那里
答案 2 :(得分:0)
https://docs.python.org/2/library/datetime.html
文档指出date.weekday()
以星期为单位返回星期几,其中星期一为0,星期日为6.所以此代码将起作用:
import datetime
# Hours must be 24 hour clock times
def is_weekday_and_time_in_range(date, start_hour, end_hour):
return date.weekday() < 5 and date.hour in range(start_hour, end_hour)
today = datetime.datetime.now()
is_weekday_and_time_in_range(today, 10, 15)