如何在Python中比较时间? [英] How to compare times in Python?
本文介绍了如何在Python中比较时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到可以进行日期比较,还有 datetime.timedelta()
,但是我很努力地寻找如何检查当前时间( datetime.datetime.now()
)比指定时间(例如上午8点)早,晚或相同,而与日期无关。
I see that date comparisons can be done and there's also datetime.timedelta()
, but I'm struggling to find out how to check if the current time (datetime.datetime.now()
) is earlier, later or the same than a specified time (e.g. 8am) regardless of the date.
推荐答案
您不能将一个特定的时间点(例如现在)与一个固定的重复发生的事件(每次早上8点发生)进行比较
You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
您可以检查现在是在今天的 上午8点之前还是之后:
You can check if now is before or after today's 8am:
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False
这篇关于如何在Python中比较时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文