[Tutor] Help with time module

Kent Johnson kent37 at tds.net
Fri May 13 15:56:17 CEST 2005


Alberto Troiano wrote:
> I have two strings like this
> 
> hour1="14:30"
> hour2="15:30"
> 
> I want to compare them like this:
> 
> if local_time between hour1 and hour2:
>     print True
> else
>     print False
> 
> Can anyone tell me how to make that comparison to work??????? (I don't know 
> how to take only the time in this format(Hour:Minutes))

time.strptime() can parse the time string to a time tuple, then you can pull out a tuple of (hours, 
minutes) and compare.

  >>> import time
  >>> time.strptime('10:23', '%H:%M')
(1900, 1, 1, 10, 23, 0, 0, 1, -1)

Here is a helper function that extracts (hours, minutes) from a provided string, or from the clock 
time if no string is given:

  >>> def getHoursMinutes(ts=None):
  ...   if ts:
  ...     t = time.strptime(ts, '%H:%M')
  ...   else:
  ...     t = time.localtime()
  ...   return (t.tm_hour, t.tm_min)
  ...
  >>> getHoursMinutes()
(9, 52)
  >>> getHoursMinutes('8:34')
(8, 34)
  >>> hour1="14:30"
  >>> hour2="15:30"
  >>> getHoursMinutes(hour1)
(14, 30)

The values returned from getHoursMinutes() can be compared directly:

  >>> getHoursMinutes(hour1) <= getHoursMinutes() <= getHoursMinutes(hour2)
False
  >>> hour1='8:56'
  >>> getHoursMinutes(hour1) <= getHoursMinutes() <= getHoursMinutes(hour2)
True

Kent



More information about the Tutor mailing list