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.
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.
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") .
>>> 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'
easy but dirty way
max(t for t in sorted(hours) if t<=now)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With