Houman
Houman

Reputation: 66320

How to check against a time value?

I would like to know if the given time is in the morning or afternoon. I am not sure if this the correct way to create Time objects in python and do comparison against. Or is there a better way?

def part_of_day_statistics(x):
    if x > time.strptime('6:00 am') and x < time.strptime('11:59 am'):
        return 'Morning' 
    if x > time.strptime('12:00 pm') and x < time.strptime('5:59 pm'):
        return 'Afternoon' 

Upvotes: 1

Views: 295

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

Django TimeField entries are datetime.time instances, which have an .hour attribute (ranging from 0 to 23):

def part_of_day_statistics(x):
    if x.hour >= 6 and x.hour < 12:
        return 'Morning'
    if x.hour >= 12 and x.hour < 18:
        return 'Afternoon'

Upvotes: 6

Related Questions