擅长:python、mysql、java
<p><code>datetime</code>对象有一个名为<code>time()</code>的方法,该方法返回一个<code>time</code>对象(没有日期信息)。然后可以使用普通的<code><</code>或<code>></code>运算符比较<code>time</code>对象。</p>
<pre><code>import datetime
import time
timestamp = datetime.datetime.now().time() # Throw away the date information
time.sleep(1)
print (datetime.datetime.now().time() > timestamp) # >>> True (unless you ran this one second before midnight!)
# Or check if a time is between two other times
start = datetime.time(8, 30)
end = datetime.time(15)
print (start <= timestamp <= end) # >>> depends on what time it is
</code></pre>
<hr/>
<p>如果您还想检查工作日,您建议的代码可能是最有效的方法,但在这种情况下,您可能不想抛出原始的<code>datetime</code>对象。</p>
<pre><code>now = datetime.datetime.now()
if 0 <= now.weekday() <= 4:
print ("It's a weekday!")
print (start <= now.time() <= end) # with start & end defined as above
</code></pre>