Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest hour

I have a list with these items:

hours = ['19:30', '20:10', '20:30', '21:00', '22:00']

Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide.

like image 683
ov1d1u Avatar asked Nov 07 '10 16:11

ov1d1u


People also ask

How to round date time to the nearest hour?

Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.

How do you round time to the nearest hour in Python?

In order to round a DateTime object to the nearest hour, you need to use the round operation from Pandas on the DateTime column and specify the frequency that you want to use. For rounding to the nearest hour you will need to use round("H") .


2 Answers

>>> import datetime
>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
>>> now = datetime.datetime.strptime("20:18", "%H:%M")
>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))
'20:10'
like image 65
Katriel Avatar answered Nov 04 '22 09:11

Katriel


easy but dirty way

max(t for t in sorted(hours) if t<=now)
like image 5
Kabie Avatar answered Nov 04 '22 09:11

Kabie