HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

filter date for a specific hour and minute

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hourdatefilterforspecificandminute

Problem

selected_hour=12
dates=[]
date1 = datetime.datetime(2012, 9, 10, 11, 46, 45)
date2 = datetime.datetime(2012, 9, 10, 12, 46, 45)
date3 = datetime.datetime(2012, 9, 10, 13, 47, 45)
date4 = datetime.datetime(2012, 9, 10, 13, 06, 45)
dates.append(date1)
dates.append(date2)
dates.append(date3)
dates.append(date4)

for i in dates:
    if (i.hour=selected_hour-1):
        if not i.hour==selected_hour:
            if i.hour==selected_hour-1 and i.minute>45:
                print i
            if i.hour==selected_hour+1 and i.minute<=15:
                print i
        if i.hour==selected_hour:
            print i


Result is :

2012-09-10 11:46:45
    2012-09-10 12:46:45
    2012-09-10 13:06:45


I want to filter my dates based on selected_hour. The output should be 15 minutes later and before of the selected_hour including all selected_hour's minutes. This codes does what I want but, i am looking for a nicer way to do that. How to get same results in a shorter and better way ?

Solution

Try something like this:

for i in dates:
    if i.hour == selected_hour:
        print i
    elif i.hour == (selected_hour - 1) % 24 and i.minute > 45:
        print i
    elif i.hour == (selected_hour + 1) % 24 and i.minute <= 15:
        print i


The biggest technique I used to condense your code basically was "Don't repeat yourself"! You have a lot of redundant if statements in your code which can be simplified.

Another thing that makes my code more understandable is that it's flat, not nested. Ideally, you'd want to minimize the number of logic branches.

Edit: As @Dougal mentioned, my original code wouldn't work on the special case of midnight. I added in a modulus operator on my two elif conditions so that the selected_hour test wraps in a 24 digit circle, just like real time.

Code Snippets

for i in dates:
    if i.hour == selected_hour:
        print i
    elif i.hour == (selected_hour - 1) % 24 and i.minute > 45:
        print i
    elif i.hour == (selected_hour + 1) % 24 and i.minute <= 15:
        print i

Context

StackExchange Code Review Q#17564, answer score: 5

Revisions (0)

No revisions yet.