views:

601

answers:

4

How do I compare times in python?

I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date.

A: 

datetime have comparison capability

>>> import datetime
>>> import time
>>> a =  datetime.datetime.now()
>>> time.sleep(2.0)
>>> b =  datetime.datetime.now()
>>> print a < b
True
>>> print a == b
False
luc
+1  A: 

You can compare datetime.datetime objects directly

E.g:

>>> a
datetime.datetime(2009, 12, 2, 10, 24, 34, 198130)
>>> b
datetime.datetime(2009, 12, 2, 10, 24, 36, 910128)
>>> a < b
True
>>> a > b
False
>>> a == a
True
>>> b == b
True
>>>
Kimvais
+5  A: 

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
Roger Pate
You might want to flip the acceptance to Pär Wieslander's answer (and generally should wait a few more minutes than you did :P), as it's a bit more specific to exactly what you asked.
Roger Pate
+7  A: 

You can use the time() method of datetime objects to get the time of day, which you can use for comparison without taking the date into account:

>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True
Pär Wieslander
+1. You can also do `now.time() < datetime.time(hour=8)`.
Roger Pate