如果我处于一天中的特定时间段,如何检查python? [英] How to check in python if I'm in certain range of times of the day?

查看:46
本文介绍了如果我处于一天中的特定时间段,如何检查python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查python当前时间是否在两个端点之间(例如,上午8:30和下午3:00),与实际日期无关.就像我一样,我不在乎整个日期是多少.只是一个小时.当我使用 strptime 创建 datetime 对象以指定时间时,它放入了一个虚拟日期(我认为是1900年?),这不是我想要的.我可以使用笨拙的布尔表达式,例如(hour == 8 and minutes> = 30)或(9< = hour< 15),但这似乎并不优雅.什么是最简单,最Python的方法来完成此任务?

I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I don't care what the full date is; just the hour. When I created datetime objects using strptime to specify a time, it threw in a dummy date (I think the year 1900?) which is not what I want. I could use a clumsy boolean expression like (hour == 8 and minute >= 30) or (9 <= hour < 15) but that doesn't seem very elegant. What's the easiest and most pythonic way to accomplish this?

再延伸一点,我真正想要的是可以告诉我是否在几个小时的范围内,又是一个工作日.当然,我可以使用 0< = weekday()< = 4 来破解,但是可能会有更好的方法.

Extending a bit further, what I'd really like is something that will tell me if it's between that range of hours, and that it's a weekday. Of course I can just use 0 <= weekday() <= 4 to hack this, but there might be a better way.

推荐答案

datetime 对象具有称为 time()的方法,该方法返回 time 对象(无日期信息).然后,您可以使用普通的< > 运算符比较 time 对象.

datetime objects have a method called time() which returns a time object (with no date information). You can then compare the time objects using the normal < or > operators.

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


如果您还想检查工作日,建议的代码可能是解决问题的最有效方法,但是在那种情况下,您可能不想扔掉原始的 datetime 对象.

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

这篇关于如果我处于一天中的特定时间段,如何检查python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆