将当前日期时间与一天中包含分钟的时间进行比较
将当前日期时间与一天中包含分钟的时间进行比较的最佳方法是什么。我目前的方法似乎不是最简洁的。我想在下午 6:30 之后执行一条语句。
from datetime import datetime as dt
if (dt.now().hour == 18 and dt.now().minute > 30) or dt.now().hour >= 19:
print('hello world')
如果我想在下午 6:30 之后和晚上 9:30 之前进行,事情会变得更加混乱。
What's the best way to compare the current datetime to a time of day that includes minutes. My current method doesn't seem the most concise. I want to execute a statement after 6:30PM.
from datetime import datetime as dt
if (dt.now().hour == 18 and dt.now().minute > 30) or dt.now().hour >= 19:
print('hello world')
It gets even messier if I want to do after 6:30PM and before 9:30PM.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需从
datetime
对象中提取time
对象并进行直接比较即可。You can simply extract a
time
object from yourdatetime
object and make a direct comparison.我会这样做:
I would do this:
您可以使用我为我的一个项目构建的这个函数。我在日、小时、分钟、秒级别上构建了这个功能。我已经根据您的需要减少了它。
您可以根据需要重复使用该功能。例如:
这本质上与使用“ Between”选项相同。
You can use this function which I built for one of my projects. I had this function built at day, hour, minute, second level. I have reduced it for your needs.
You can reuse the function for your need. For eg:
This is essentially the same as using the "between" option.