How to compare times in Python?

Steve Jay picture Steve Jay · Dec 2, 2009 · Viewed 198.3k times · Source

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.

Answer

Roger Pate picture Roger Pate · Dec 2, 2009

You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).

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