2012-08-04 26 views
1

我想知道,如果給定的時間是在早上或下午。我不知道這是否正確的方法在Python中創建對象的時間,做對的比較。或者,還有更好的方法?如何檢查對時間值?

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' 
+0

推測'x'是Unix時間戳(從epoch秒)? – 2012-08-04 16:16:13

+0

對不起,沒有它是在Django'contact_time = models.TimeField時間字段()' – Houman 2012-08-04 16:17:45

+0

啊,那是一個'datetime.time'場.. – 2012-08-04 16:20:53

回答

6

的Django TimeField entriesdatetime.time instances,其具有.hour屬性(範圍從0至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' 
+0

神奇。這比我想象的要簡單得多。 :) 謝謝 – Houman 2012-08-04 16:24:26