日期时间比较

时间:2015-11-05 20:37:33

标签: python-2.7 datetime

我可以用

检查时间A是否晚于时间B
Recipe.joins(:ingredients)
.where('recipe_ingredients.require_in_filter = ? AND recipe_ingredients.product_id IN (?)', true, [3,4])
.group('recipe_ingredients.product_id').having('COUNT(*) = ?', 2)

但过去午夜做同样的伎俩是什么?

A.time() > B.time():

我希望脚本能在18:30之后列出所有电影,但它会错过最后一部电影。我应该存储所有电影的日期时间并以这种方式进行比较还是有更简单的方法?

1 个答案:

答案 0 :(得分:1)

您可以假设您的一天在下午6点(例如)下一个日期结束。换句话说,“02:15 Drive-In Dinosaur Disaster”属于下一个日期,但是对于你来说它虽然在午夜之后也是同一个日期。如果您只需要比较小时和分钟,可以将日期时间减少6个小时,如下所示:

movies = [
"13:00 Alien Beetroot",
"15:30 Bananas Go Bad!",
"17:45 Cheerleader Lake",
"19:00 Yoghurt Spoon Eater",
"21:10 Zombie A Go-Go",
"23:30 Shark Snacks VI",
"02:15 Drive-In Dinosaur Disaster"
]

myTime = (18, 30) # hours and minutes

myTime_reduced = ((myTime[0] - 6) % 24, myTime[1]) # the mentioned reduce

for i in range(0, len(movies)):
    sp = movies[i].split(" ", 1)
    tim = sp[0]
    mov = sp[1]

    h, m = tim.split(':')

    h_reduced = (h - 6) % 24 # the mentioned reduce

    if h_reduced > myTime_reduced[0] or (h_reduced == myTime_reduced[0] and m > myTime_reduced[1]):
        print tim + " " + mov